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
fix(lowest_tpm_rpm_v2.py): support batch writing increments to redis
Krrish Dholakia1328afe612b7
diff --git a/litellm/constants.py b/litellm/constants.pyindex b4551a78f5f..eb59858d433 100644--- a/litellm/constants.py+++ b/litellm/constants.py@@ -7,6 +7,7 @@ DEFAULT_MAX_RETRIES = 2DEFAULT_FAILURE_THRESHOLD_PERCENT = (0.5 # default cooldown a deployment if 50% of requests fail in a given minute)+DEFAULT_REDIS_SYNC_INTERVAL = 1DEFAULT_COOLDOWN_TIME_SECONDS = 5DEFAULT_REPLICATE_POLLING_RETRIES = 5DEFAULT_REPLICATE_POLLING_DELAY_SECONDS = 1diff --git a/litellm/proxy/_experimental/out/onboarding.html b/litellm/proxy/_experimental/out/onboarding.htmldeleted file mode 100644index 82f43619df3..00000000000--- a/litellm/proxy/_experimental/out/onboarding.html+++ /dev/null@@ -1 +0,0 @@-<!DOCTYPE html><html id="__next_error__"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="preload" as="script" fetchPriority="low" href="/ui/_next/static/chunks/webpack-75a5453f51d60261.js"/><script src="/ui/_next/static/chunks/fd9d1056-524b80e1a6b8bb06.js" async=""></script><script src="/ui/_next/static/chunks/117-883150efc583d711.js" async=""></script><script src="/ui/_next/static/chunks/main-app-475d6efe4080647d.js" async=""></script><title>LiteLLM Dashboard</title><meta name="description" content="LiteLLM Proxy Admin UI"/><link rel="icon" href="/ui/favicon.ico" type="image/x-icon" sizes="16x16"/><meta name="next-size-adjust"/><script src="/ui/_next/static/chunks/polyfills-42372ed130431b0a.js" noModule=""></script></head><body><script src="/ui/_next/static/chunks/webpack-75a5453f51d60261.js" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0]);self.__next_f.push([2,null])</script><script>self.__next_f.push([1,"1:HL[\"/ui/_next/static/media/a34f9d1faa5f3315-s.p.woff2\",\"font\",{\"crossOrigin\":\"\",\"type\":\"font/woff2\"}]\n2:HL[\"/ui/_next/static/css/86f6cc749f6b8493.css\",\"style\"]\n3:HL[\"/ui/_next/static/css/169f9187db1ec37e.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"4:I[12846,[],\"\"]\n6:I[19107,[],\"ClientPageRoot\"]\n7:I[12011,[\"665\",\"static/chunks/3014691f-0b72c78cfebbd712.js\",\"42\",\"static/chunks/42-1cbed529ecb084e0.js\",\"899\",\"static/chunks/899-9af4feaf6f21839c.js\",\"250\",\"static/chunks/250-a75ee9d79f1140b0.js\",\"461\",\"static/chunks/app/onboarding/page-1ffe69692e4b2037.js\"],\"default\",1]\n8:I[4707,[],\"\"]\n9:I[36423,[],\"\"]\nb:I[61060,[],\"\"]\nc:[]\n"])</script><script>self.__next_f.push([1,"0:[\"$\",\"$L4\",null,{\"buildId\":\"9yIyUkG6nV2cO0gn7kJ-Q\",\"assetPrefix\":\"/ui\",\"urlParts\":[\"\",\"onboarding\"],\"initialTree\":[\"\",{\"children\":[\"onboarding\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",true],\"initialSeedData\":[\"\",{\"children\":[\"onboarding\",{\"children\":[\"__PAGE__\",{},[[\"$L5\",[\"$\",\"$L6\",null,{\"props\":{\"params\":{},\"searchParams\":{}},\"Component\":\"$7\"}],null],null],null]},[null,[\"$\",\"$L8\",null,{\"parallelRouterKey\":\"children\",\"segmentPath\":[\"children\",\"onboarding\",\"children\"],\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L9\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"notFoundStyles\":\"$undefined\"}]],null]},[[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/ui/_next/static/css/86f6cc749f6b8493.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\"}],[\"$\",\"link\",\"1\",{\"rel\":\"stylesheet\",\"href\":\"/ui/_next/static/css/169f9187db1ec37e.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"children\":[\"$\",\"body\",null,{\"className\":\"__className_cf7686\",\"children\":[\"$\",\"$L8\",null,{\"parallelRouterKey\":\"children\",\"segmentPath\":[\"children\"],\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L9\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":\"404\"}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],\"notFoundStyles\":[]}]}]}]],null],null],\"couldBeIntercepted\":false,\"initialHead\":[null,\"$La\"],\"globalErrorComponent\":\"$b\",\"missingSlots\":\"$Wc\"}]\n"])</script><script>self.__next_f.push([1,"a:[[\"$\",\"meta\",\"0\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}],[\"$\",\"meta\",\"1\",{\"charSet\":\"utf-8\"}],[\"$\",\"title\",\"2\",{\"children\":\"LiteLLM Dashboard\"}],[\"$\",\"meta\",\"3\",{\"name\":\"description\",\"content\":\"LiteLLM Proxy Admin UI\"}],[\"$\",\"link\",\"4\",{\"rel\":\"icon\",\"href\":\"/ui/favicon.ico\",\"type\":\"image/x-icon\",\"sizes\":\"16x16\"}],[\"$\",\"meta\",\"5\",{\"name\":\"next-size-adjust\"}]]\n5:null\n"])</script></body></html>\ No newline at end of filediff --git a/litellm/proxy/_new_secret_config.yaml b/litellm/proxy/_new_secret_config.yamlindex 64100277a80..00b3f325b0d 100644--- a/litellm/proxy/_new_secret_config.yaml+++ b/litellm/proxy/_new_secret_config.yaml@@ -3,13 +3,13 @@ model_list:litellm_params:model: azure/chatgpt-v-2api_key: os.environ/AZURE_API_KEY- api_base: os.environ/AZURE_API_BASE+ api_base: http://0.0.0.0:8090litellm_settings:- callbacks: ["prometheus"]+ callbacks: ["otel"]router_settings:- routing_strategy: usage-based-routing-v2 # 👈 KEY CHANGE+ # routing_strategy: usage-based-routing-v2 # 👈 KEY CHANGEredis_host: os.environ/REDIS_HOSTredis_password: os.environ/REDIS_PASSWORDredis_port: os.environ/REDIS_PORTdiff --git a/litellm/router_strategy/base_routing_strategy.py b/litellm/router_strategy/base_routing_strategy.pynew file mode 100644index 00000000000..b9a2f9cf04b--- /dev/null+++ b/litellm/router_strategy/base_routing_strategy.py@@ -0,0 +1,154 @@+"""+Base class across routing strategies to abstract commmon functions like batch incrementing redis+"""++import asyncio+from abc import ABC, abstractmethod+from typing import List, Optional, Union++from litellm._logging import verbose_router_logger+from litellm.caching.caching import DualCache+from litellm.caching.redis_cache import RedisPipelineIncrementOperation+from litellm.constants import DEFAULT_REDIS_SYNC_INTERVAL+++class BaseRoutingStrategy(ABC):+ def __init__(+ self,+ dual_cache: DualCache,+ should_batch_redis_writes: bool,+ default_sync_interval: Optional[Union[int, float]],+ ):+ self.dual_cache = dual_cache+ self.redis_increment_operation_queue: List[RedisPipelineIncrementOperation] = []+ if should_batch_redis_writes:+ asyncio.create_task(+ self.periodic_sync_in_memory_spend_with_redis(+ default_sync_interval=default_sync_interval+ )+ )++ async def _increment_value_in_current_window(+ self, key: str, value: Union[int, float], ttl: int+ ):+ """+ Increment spend within existing budget window++ Runs once the budget start time exists in Redis Cache (on the 2nd and subsequent requests to the same provider)++ - Increments the spend in memory cache (so spend instantly updated in memory)+ - Queues the increment operation to Redis Pipeline (using batched pipeline to optimize performance. Using Redis for multi instance environment of LiteLLM)+ """+ result = await self.dual_cache.in_memory_cache.async_increment(+ key=key,+ value=value,+ ttl=ttl,+ )+ increment_op = RedisPipelineIncrementOperation(+ key=key,+ increment_value=value,+ ttl=ttl,+ )+ self.redis_increment_operation_queue.append(increment_op)++ return result++ async def periodic_sync_in_memory_spend_with_redis(+ self, default_sync_interval: Optional[Union[int, float]]+ ):+ """+ Handler that triggers sync_in_memory_spend_with_redis every DEFAULT_REDIS_SYNC_INTERVAL seconds++ Required for multi-instance environment usage of provider budgets+ """+ default_sync_interval = default_sync_interval or DEFAULT_REDIS_SYNC_INTERVAL+ while True:+ try:+ await self._sync_in_memory_spend_with_redis()+ await asyncio.sleep(+ default_sync_interval+ ) # Wait for DEFAULT_REDIS_SYNC_INTERVAL seconds before next sync+ except Exception as e:+ verbose_router_logger.error(f"Error in periodic sync task: {str(e)}")+ await asyncio.sleep(+ default_sync_interval+ ) # Still wait DEFAULT_REDIS_SYNC_INTERVAL seconds on error before retrying++ async def _push_in_memory_increments_to_redis(self):+ """+ How this works:+ - async_log_success_event collects all provider spend increments in `redis_increment_operation_queue`+ - This function pushes all increments to Redis in a batched pipeline to optimize performance++ Only runs if Redis is initialized+ """+ try:+ if not self.dual_cache.redis_cache:+ return # Redis is not initialized++ verbose_router_logger.debug(+ "Pushing Redis Increment Pipeline for queue: %s",+ self.redis_increment_operation_queue,+ )+ if len(self.redis_increment_operation_queue) > 0:+ asyncio.create_task(+ self.dual_cache.redis_cache.async_increment_pipeline(+ increment_list=self.redis_increment_operation_queue,+ )+ )++ self.redis_increment_operation_queue = []++ except Exception as e:+ verbose_router_logger.error(+ f"Error syncing in-memory cache with Redis: {str(e)}"+ )++ @abstractmethod+ def get_cache_keys(self) -> List:+ pass++ async def _sync_in_memory_spend_with_redis(self):+ """+ Ensures in-memory cache is updated with latest Redis values for all provider spends.++ Why Do we need this?+ - Optimization to hit sub 100ms latency. Performance was impacted when redis was used for read/write per request+ - Use provider budgets in multi-instance environment, we use Redis to sync spend across all instances++ What this does:+ 1. Push all provider spend increments to Redis+ 2. Fetch all current provider spend from Redis to update in-memory cache+ """++ try:+ # No need to sync if Redis cache is not initialized+ if self.dual_cache.redis_cache is None:+ return++ # 1. Push all provider spend increments to Redis+ await self._push_in_memory_increments_to_redis()++ # 2. Fetch all current provider spend from Redis to update in-memory cache+ cache_keys = self.get_cache_keys()++ # Batch fetch current spend values from Redis+ redis_values = await self.dual_cache.redis_cache.async_batch_get_cache(+ key_list=cache_keys+ )++ # Update in-memory cache with Redis values+ if isinstance(redis_values, dict): # Check if redis_values is a dictionary+ for key, value in redis_values.items():+ if value is not None:+ await self.dual_cache.in_memory_cache.async_set_cache(+ key=key, value=float(value)+ )+ verbose_router_logger.debug(+ f"Updated in-memory cache for {key}: {value}"+ )++ except Exception as e:+ verbose_router_logger.error(+ f"Error syncing in-memory cache with Redis: {str(e)}"+ )diff --git a/litellm/router_strategy/lowest_tpm_rpm_v2.py b/litellm/router_strategy/lowest_tpm_rpm_v2.pyindex 64f086036be..45bb14ee028 100644--- a/litellm/router_strategy/lowest_tpm_rpm_v2.py+++ b/litellm/router_strategy/lowest_tpm_rpm_v2.py@@ -15,6 +15,8 @@ from litellm.types.router import RouterErrorsfrom litellm.types.utils import LiteLLMPydanticObjectBase, StandardLoggingPayloadfrom litellm.utils import get_utc_datetime, print_verbose+from .base_routing_strategy import BaseRoutingStrategy+if TYPE_CHECKING:from opentelemetry.trace import Span as _Span@@ -27,7 +29,7 @@ class RoutingArgs(LiteLLMPydanticObjectBase):ttl: int = 1 * 60 # 1min (RPM/TPM expire key)-class LowestTPMLoggingHandler_v2(CustomLogger):+class LowestTPMLoggingHandler_v2(BaseRoutingStrategy, CustomLogger):"""Updated version of TPM/RPM Logging.@@ -51,6 +53,12 @@ class LowestTPMLoggingHandler_v2(CustomLogger):self.router_cache = router_cacheself.model_list = model_listself.routing_args = RoutingArgs(**routing_args)+ BaseRoutingStrategy.__init__(+ self,+ dual_cache=router_cache,+ should_batch_redis_writes=True,+ default_sync_interval=0.1,+ )def pre_call_check(self, deployment: Dict) -> Optional[Dict]:"""@@ -104,6 +112,7 @@ class LowestTPMLoggingHandler_v2(CustomLogger):)else:# if local result below limit, check redis ## prevent unnecessary redis checks+result = self.router_cache.increment_cache(key=rpm_key, value=1, ttl=self.routing_args.ttl)@@ -186,12 +195,15 @@ class LowestTPMLoggingHandler_v2(CustomLogger):)else:# if local result below limit, check redis ## prevent unnecessary redis checks- result = await self.router_cache.async_increment_cache(- key=rpm_key,- value=1,- ttl=self.routing_args.ttl,- parent_otel_span=parent_otel_span,+ result = await self._increment_value_in_current_window(+ key=rpm_key, value=1, ttl=self.routing_args.ttl)+ # result = await self.router_cache.async_increment_cache(+ # key=rpm_key,+ # value=1,+ # ttl=self.routing_args.ttl,+ # parent_otel_span=parent_otel_span,+ # )if result is not None and result > deployment_rpm:raise litellm.RateLimitError(message="Deployment over defined rpm limit={}. current usage={}".format(