Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /BerriAI_litellm /litellm /router_strategy /lowest_latency.py
| #### What this does #### | |
| # picks based on response time (for streaming, this is time to first token) | |
| import random | |
| from collections.abc import Sequence | |
| from datetime import datetime, timedelta | |
| from typing import TYPE_CHECKING, Any, Final | |
| import litellm | |
| from litellm import ModelResponse, token_counter, verbose_logger | |
| from litellm.caching.caching import DualCache | |
| from litellm.integrations.custom_logger import CustomLogger | |
| from litellm.litellm_core_utils.core_helpers import _get_parent_otel_span_from_kwargs, safe_divide_seconds | |
| from litellm.types.utils import LiteLLMPydanticObjectBase | |
| if TYPE_CHECKING: | |
| from opentelemetry.trace import Span as _Span | |
| Span = _Span | |
| else: | |
| Span = Any | |
| class RoutingArgs(LiteLLMPydanticObjectBase): | |
| ttl: float = 1 * 60 * 60 # 1 hour | |
| lowest_latency_buffer: float = 0 | |
| max_latency_list_size: int = 10 | |
| def _average_latency(samples: Sequence[float]) -> float: | |
| if not samples: | |
| return 0.0 | |
| return sum(samples) / len(samples) | |
| def _ttft_seconds(elapsed: timedelta | float) -> float: | |
| if isinstance(elapsed, timedelta): | |
| return elapsed.total_seconds() | |
| return float(elapsed) | |
| class LowestLatencyLoggingHandler(CustomLogger): | |
| test_flag: bool = False | |
| logged_success: int = 0 | |
| logged_failure: int = 0 | |
| def __init__(self, router_cache: DualCache, routing_args: dict = {}): | |
| self.router_cache = router_cache | |
| self.routing_args = RoutingArgs(**routing_args) | |
| def log_success_event(self, kwargs, response_obj, start_time, end_time): | |
| try: | |
| """ | |
| Update latency usage on success | |
| """ | |
| metadata_field: Final = self._select_metadata_field(kwargs) | |
| if kwargs["litellm_params"].get(metadata_field) is None: | |
| pass | |
| else: | |
| model_group: Final = kwargs["litellm_params"][metadata_field].get("model_group", None) | |
| id = (kwargs["litellm_params"].get("model_info") or {}).get("id", None) | |
| if model_group is None or id is None: | |
| return | |
| elif isinstance(id, int): | |
| id = str(id) | |
| # ------------ | |
| # Setup values | |
| # ------------ | |
| """ | |
| { | |
| {model_group}_map: { | |
| id: { | |
| "latency": [..] | |
| f"{date:hour:minute}" : {"tpm": 34, "rpm": 3} | |
| } | |
| } | |
| } | |
| """ | |
| latency_key: Final = f"{model_group}_map" | |
| current_date: Final = datetime.now().strftime("%Y-%m-%d") | |
| current_hour: Final = datetime.now().strftime("%H") | |
| current_minute: Final = datetime.now().strftime("%M") | |
| precise_minute: Final = f"{current_date}-{current_hour}-{current_minute}" | |
| response_ms = end_time - start_time | |
| if isinstance(response_ms, timedelta): | |
| # normalize to float seconds up-front: non-chat responses | |
| # (embeddings, speech, image) skip the ModelResponse branch | |
| # below, and a raw timedelta appended to the latency list | |
| # breaks JSON serialization when the router cache syncs to | |
| # Redis (issue #33169) | |
| response_ms = response_ms.total_seconds() | |
| time_to_first_token: float | None = None | |
| if kwargs.get("stream", None) is not None and kwargs["stream"] is True: | |
| # only log ttft for streaming request | |
| time_to_first_token = _ttft_seconds(kwargs.get("completion_start_time", end_time) - start_time) | |
| final_value: float = response_ms | |
| total_tokens = 0 | |
| if isinstance(response_obj, ModelResponse): | |
| _usage: Final = getattr(response_obj, "usage", None) | |
| if _usage is not None: | |
| completion_tokens: Final = _usage.completion_tokens | |
| total_tokens = _usage.total_tokens | |
| # response_ms is already normalized to float seconds above | |
| response_seconds: Final = response_ms | |
| normalized_value: Final = safe_divide_seconds(response_seconds, completion_tokens) | |
| if normalized_value is not None: | |
| final_value = float(normalized_value) | |
| else: | |
| final_value = response_seconds | |
| # ------------ | |
| # Update usage | |
| # ------------ | |
| parent_otel_span: Final = _get_parent_otel_span_from_kwargs(kwargs) | |
| request_count_dict: Final = ( | |
| self.router_cache.get_cache(key=latency_key, parent_otel_span=parent_otel_span) or {} | |
| ) | |
| if id not in request_count_dict: | |
| request_count_dict[id] = {} | |
| ## Latency | |
| if len(request_count_dict[id].get("latency", [])) < self.routing_args.max_latency_list_size: | |
| request_count_dict[id].setdefault("latency", []).append(final_value) | |
| else: | |
| request_count_dict[id]["latency"] = request_count_dict[id]["latency"][1:] + [final_value] | |
| ## Time to first token | |
| if time_to_first_token is not None: | |
| if ( | |
| len(request_count_dict[id].get("time_to_first_token_seconds", [])) | |
| < self.routing_args.max_latency_list_size | |
| ): | |
| request_count_dict[id].setdefault("time_to_first_token_seconds", []).append(time_to_first_token) | |
| else: | |
| request_count_dict[id]["time_to_first_token_seconds"] = request_count_dict[id][ | |
| "time_to_first_token_seconds" | |
| ][1:] + [time_to_first_token] | |
| if precise_minute not in request_count_dict[id]: | |
| request_count_dict[id][precise_minute] = {} | |
| ## TPM | |
| request_count_dict[id][precise_minute]["tpm"] = ( | |
| request_count_dict[id][precise_minute].get("tpm", 0) + total_tokens | |
| ) | |
| ## RPM | |
| request_count_dict[id][precise_minute]["rpm"] = request_count_dict[id][precise_minute].get("rpm", 0) + 1 | |
| self.router_cache.set_cache( | |
| key=latency_key, value=request_count_dict, ttl=self.routing_args.ttl | |
| ) # reset map within window | |
| ### TESTING ### | |
| if self.test_flag: | |
| self.logged_success += 1 | |
| except Exception as e: | |
| verbose_logger.exception( | |
| "litellm.proxy.hooks.prompt_injection_detection.py::async_pre_call_hook(): Exception occured - %s", e | |
| ) | |
| async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): | |
| """ | |
| Check if Timeout Error, if timeout set deployment latency -> 100 | |
| """ | |
| try: | |
| metadata_field: Final = self._select_metadata_field(kwargs) | |
| _exception: Final = kwargs.get("exception", None) | |
| if isinstance(_exception, litellm.Timeout): | |
| if kwargs["litellm_params"].get(metadata_field) is None: | |
| pass | |
| else: | |
| model_group: Final = kwargs["litellm_params"][metadata_field].get("model_group", None) | |
| id = (kwargs["litellm_params"].get("model_info") or {}).get("id", None) | |
| if model_group is None or id is None: | |
| return | |
| elif isinstance(id, int): | |
| id = str(id) | |
| # ------------ | |
| # Setup values | |
| # ------------ | |
| """ | |
| { | |
| {model_group}_map: { | |
| id: { | |
| "latency": [..] | |
| f"{date:hour:minute}" : {"tpm": 34, "rpm": 3} | |
| } | |
| } | |
| } | |
| """ | |
| latency_key: Final = f"{model_group}_map" | |
| request_count_dict: Final = await self.router_cache.async_get_cache(key=latency_key) or {} | |
| if id not in request_count_dict: | |
| request_count_dict[id] = {} | |
| ## Latency - give 1000s penalty for failing | |
| if len(request_count_dict[id].get("latency", [])) < self.routing_args.max_latency_list_size: | |
| request_count_dict[id].setdefault("latency", []).append(1000.0) | |
| else: | |
| request_count_dict[id]["latency"] = request_count_dict[id]["latency"][1:] + [1000.0] | |
| await self.router_cache.async_set_cache( | |
| key=latency_key, | |
| value=request_count_dict, | |
| ttl=self.routing_args.ttl, | |
| ) # reset map within window | |
| else: | |
| # do nothing if it's not a timeout error | |
| return | |
| except Exception as e: | |
| verbose_logger.exception( | |
| "litellm.proxy.hooks.prompt_injection_detection.py::async_pre_call_hook(): Exception occured - %s", e | |
| ) | |
| async def async_log_success_event(self, kwargs, response_obj, start_time, end_time): | |
| try: | |
| """ | |
| Update latency usage on success | |
| """ | |
| metadata_field: Final = self._select_metadata_field(kwargs) | |
| if kwargs["litellm_params"].get(metadata_field) is None: | |
| pass | |
| else: | |
| model_group: Final = kwargs["litellm_params"][metadata_field].get("model_group", None) | |
| id = (kwargs["litellm_params"].get("model_info") or {}).get("id", None) | |
| if model_group is None or id is None: | |
| return | |
| elif isinstance(id, int): | |
| id = str(id) | |
| # ------------ | |
| # Setup values | |
| # ------------ | |
| """ | |
| { | |
| {model_group}_map: { | |
| id: { | |
| "latency": [..] | |
| "time_to_first_token_seconds": [..] | |
| f"{date:hour:minute}" : {"tpm": 34, "rpm": 3} | |
| } | |
| } | |
| } | |
| """ | |
| latency_key: Final = f"{model_group}_map" | |
| current_date: Final = datetime.now().strftime("%Y-%m-%d") | |
| current_hour: Final = datetime.now().strftime("%H") | |
| current_minute: Final = datetime.now().strftime("%M") | |
| precise_minute: Final = f"{current_date}-{current_hour}-{current_minute}" | |
| response_ms = end_time - start_time | |
| if isinstance(response_ms, timedelta): | |
| # normalize to float seconds up-front: non-chat responses | |
| # (embeddings, speech, image) skip the ModelResponse branch | |
| # below, and a raw timedelta appended to the latency list | |
| # breaks JSON serialization when the router cache syncs to | |
| # Redis (issue #33169) | |
| response_ms = response_ms.total_seconds() | |
| time_to_first_token: float | None = None | |
| if kwargs.get("stream", None) is not None and kwargs["stream"] is True: | |
| # only log ttft for streaming request | |
| time_to_first_token = _ttft_seconds(kwargs.get("completion_start_time", end_time) - start_time) | |
| final_value: float = response_ms | |
| total_tokens = 0 | |
| if isinstance(response_obj, ModelResponse): | |
| _usage: Final = getattr(response_obj, "usage", None) | |
| if _usage is not None: | |
| completion_tokens: Final = _usage.completion_tokens | |
| total_tokens = _usage.total_tokens | |
| # response_ms is already normalized to float seconds above | |
| response_seconds: Final = response_ms | |
| normalized_value: Final = safe_divide_seconds(response_seconds, completion_tokens) | |
| if normalized_value is not None: | |
| final_value = float(normalized_value) | |
| else: | |
| final_value = response_seconds | |
| # ------------ | |
| # Update usage | |
| # ------------ | |
| parent_otel_span: Final = _get_parent_otel_span_from_kwargs(kwargs) | |
| request_count_dict: Final = ( | |
| await self.router_cache.async_get_cache( | |
| key=latency_key, | |
| parent_otel_span=parent_otel_span, | |
| local_only=True, | |
| ) | |
| or {} | |
| ) | |
| if id not in request_count_dict: | |
| request_count_dict[id] = {} | |
| ## Latency | |
| if len(request_count_dict[id].get("latency", [])) < self.routing_args.max_latency_list_size: | |
| request_count_dict[id].setdefault("latency", []).append(final_value) | |
| else: | |
| request_count_dict[id]["latency"] = request_count_dict[id]["latency"][1:] + [final_value] | |
| ## Time to first token | |
| if time_to_first_token is not None: | |
| if ( | |
| len(request_count_dict[id].get("time_to_first_token_seconds", [])) | |
| < self.routing_args.max_latency_list_size | |
| ): | |
| request_count_dict[id].setdefault("time_to_first_token_seconds", []).append(time_to_first_token) | |
| else: | |
| request_count_dict[id]["time_to_first_token_seconds"] = request_count_dict[id][ | |
| "time_to_first_token_seconds" | |
| ][1:] + [time_to_first_token] | |
| if precise_minute not in request_count_dict[id]: | |
| request_count_dict[id][precise_minute] = {} | |
| ## TPM | |
| request_count_dict[id][precise_minute]["tpm"] = ( | |
| request_count_dict[id][precise_minute].get("tpm", 0) + total_tokens | |
| ) | |
| ## RPM | |
| request_count_dict[id][precise_minute]["rpm"] = request_count_dict[id][precise_minute].get("rpm", 0) + 1 | |
| await self.router_cache.async_set_cache( | |
| key=latency_key, value=request_count_dict, ttl=self.routing_args.ttl | |
| ) # reset map within window | |
| ### TESTING ### | |
| if self.test_flag: | |
| self.logged_success += 1 | |
| except Exception as e: | |
| verbose_logger.exception( | |
| "litellm.router_strategy.lowest_latency.py::async_log_success_event(): Exception occured - %s", e | |
| ) | |
| def _get_available_deployments( | |
| self, | |
| model_group: str, | |
| healthy_deployments: list, | |
| messages: list[dict[str, str]] | None = None, | |
| input: str | list | None = None, | |
| request_kwargs: dict | None = None, | |
| request_count_dict: dict | None = None, | |
| ): | |
| """Common logic for both sync and async get_available_deployments""" | |
| # ----------------------- | |
| # Find lowest used model | |
| # ---------------------- | |
| _latency_per_deployment: Final = {} | |
| lowest_latency = float("inf") | |
| current_date: Final = datetime.now().strftime("%Y-%m-%d") | |
| current_hour: Final = datetime.now().strftime("%H") | |
| current_minute: Final = datetime.now().strftime("%M") | |
| precise_minute: Final = f"{current_date}-{current_hour}-{current_minute}" | |
| deployment = None | |
| if request_count_dict is None: # base case | |
| return | |
| all_deployments = request_count_dict | |
| for d in healthy_deployments: | |
| ## if healthy deployment not yet used | |
| if d["model_info"]["id"] not in all_deployments: | |
| all_deployments[d["model_info"]["id"]] = { | |
| "latency": [0], | |
| precise_minute: {"tpm": 0, "rpm": 0}, | |
| } | |
| try: | |
| input_tokens = token_counter(messages=messages, text=input) | |
| except Exception: | |
| input_tokens = 0 | |
| # randomly sample from all_deployments, incase all deployments have latency=0.0 | |
| _items: Final = all_deployments.items() | |
| _all_deployments: Final = random.sample(list(_items), len(_items)) | |
| all_deployments = dict(_all_deployments) | |
| ### GET AVAILABLE DEPLOYMENTS ### filter out any deployments > tpm/rpm limits | |
| potential_deployments: Final = [] | |
| for item, item_map in all_deployments.items(): | |
| ## get the item from model list | |
| _deployment = None | |
| for m in healthy_deployments: | |
| if item == m["model_info"]["id"]: | |
| _deployment = m | |
| if _deployment is None: | |
| continue # skip to next one | |
| _deployment_tpm = ( | |
| _deployment.get("tpm", None) | |
| or _deployment.get("litellm_params", {}).get("tpm", None) | |
| or _deployment.get("model_info", {}).get("tpm", None) | |
| or float("inf") | |
| ) | |
| _deployment_rpm = ( | |
| _deployment.get("rpm", None) | |
| or _deployment.get("litellm_params", {}).get("rpm", None) | |
| or _deployment.get("model_info", {}).get("rpm", None) | |
| or float("inf") | |
| ) | |
| item_latency = item_map.get("latency", []) | |
| item_ttft_latency = item_map.get("time_to_first_token_seconds", []) | |
| item_rpm = item_map.get(precise_minute, {}).get("rpm", 0) | |
| item_tpm = item_map.get(precise_minute, {}).get("tpm", 0) | |
| # get average latency or average ttft (depending on streaming/non-streaming) | |
| use_ttft = ( | |
| request_kwargs is not None | |
| and request_kwargs.get("stream", None) is not None | |
| and request_kwargs["stream"] is True | |
| and len(item_ttft_latency) > 0 | |
| ) | |
| average_latency = _average_latency(item_ttft_latency if use_ttft else item_latency) | |
| # -------------- # | |
| # Debugging Logic | |
| # -------------- # | |
| # We use _latency_per_deployment to log to langfuse, slack - this is not used to make a decision on routing | |
| # this helps a user to debug why the router picked a specfic deployment # | |
| _deployment_api_base = _deployment.get("litellm_params", {}).get("api_base", "") | |
| if _deployment_api_base is not None: | |
| _latency_per_deployment[_deployment_api_base] = average_latency | |
| # -------------- # | |
| # End of Debugging Logic | |
| # -------------- # | |
| if ( | |
| item_tpm + input_tokens > _deployment_tpm or item_rpm + 1 > _deployment_rpm | |
| ): # if user passed in tpm / rpm in the model_list | |
| continue | |
| else: | |
| potential_deployments.append((_deployment, average_latency)) | |
| if len(potential_deployments) == 0: | |
| return None | |
| # Sort potential deployments by latency | |
| sorted_deployments: Final = sorted(potential_deployments, key=lambda x: x[1]) | |
| # Find lowest latency deployment | |
| lowest_latency = sorted_deployments[0][1] | |
| # Find deployments within buffer of lowest latency | |
| buffer: Final = self.routing_args.lowest_latency_buffer * lowest_latency | |
| valid_deployments: Final = [x for x in sorted_deployments if x[1] <= lowest_latency + buffer] | |
| # Pick a random deployment from valid deployments | |
| random_valid_deployment: Final = random.choice(valid_deployments) | |
| deployment = random_valid_deployment[0] | |
| metadata_field: Final = self._select_metadata_field(request_kwargs) | |
| if request_kwargs is not None and metadata_field in request_kwargs: | |
| request_kwargs[metadata_field]["_latency_per_deployment"] = _latency_per_deployment | |
| return deployment | |
| async def async_get_available_deployments( | |
| self, | |
| model_group: str, | |
| healthy_deployments: list, | |
| messages: list[dict[str, str]] | None = None, | |
| input: str | list | None = None, | |
| request_kwargs: dict | None = None, | |
| ): | |
| # get list of potential deployments | |
| latency_key: Final = f"{model_group}_map" | |
| parent_otel_span: Final[Span | None] = _get_parent_otel_span_from_kwargs(request_kwargs) | |
| request_count_dict: Final = ( | |
| await self.router_cache.async_get_cache(key=latency_key, parent_otel_span=parent_otel_span) or {} | |
| ) | |
| return self._get_available_deployments( | |
| model_group, | |
| healthy_deployments, | |
| messages, | |
| input, | |
| request_kwargs, | |
| request_count_dict, | |
| ) | |
| def get_available_deployments( | |
| self, | |
| model_group: str, | |
| healthy_deployments: list, | |
| messages: list[dict[str, str]] | None = None, | |
| input: str | list | None = None, | |
| request_kwargs: dict | None = None, | |
| ): | |
| """ | |
| Returns a deployment with the lowest latency | |
| """ | |
| # get list of potential deployments | |
| latency_key: Final = f"{model_group}_map" | |
| parent_otel_span: Final[Span | None] = _get_parent_otel_span_from_kwargs(request_kwargs) | |
| request_count_dict = self.router_cache.get_cache(key=latency_key, parent_otel_span=parent_otel_span) or {} | |
| return self._get_available_deployments( | |
| model_group, | |
| healthy_deployments, | |
| messages, | |
| input, | |
| request_kwargs, | |
| request_count_dict, | |
| ) | |
Xet Storage Details
- Size:
- 22.5 kB
- Xet hash:
- 17d965d50da59a812567fb136c70876abc92126a0c00c5d897d4198ceed0c22c
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.