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
chore: merge main into fix/batch-retrieve-model-group
mateo-berrif8fe7045161e
diff --cc litellm/router_strategy/least_busy.pyindex e93288fd9fe,0b73f4e31a7..9ab670e4b95--- a/litellm/router_strategy/least_busy.py+++ b/litellm/router_strategy/least_busy.py@@@ -1,18 -1,111 +1,114 @@@- #### What this does ####- # identifies least busy deployment- # How is this achieved?- # - Before each call, have the router print the state of requests {"deployment": "requests_in_flight"}- # - use litellm.input_callbacks to log when a request is just about to be made to a model - {"deployment-id": traffic}- # - use litellm.success + failure callbacks to log when a request completed- # - in get_available_deployment, for a given model group name -> pick based on traffic-- import random+ import logging+ from collections.abc import Mapping, Sequencefrom typing import Final+ from pydantic import TypeAdapter, ValidationError+ from typing_extensions import ReadOnly, TypedDict++ from litellm._logging import verbose_router_loggerfrom litellm.caching.caching import DualCache+ from litellm.caching.redis_cache import log_redis_failurefrom litellm.integrations.custom_logger import CustomLogger+from litellm.router_utils.batch_utils import is_batch_retrieve_call_type+ IN_FLIGHT_COUNT_TTL_SECONDS: Final = 60 * 60+++ class _ModelInfo(TypedDict, total=False):+ id: ReadOnly[str | int | None]+++ class _Metadata(TypedDict, total=False):+ model_group: ReadOnly[str | None]+++ class _LitellmParams(TypedDict, total=False):+ metadata: ReadOnly[_Metadata | None]+ model_info: ReadOnly[_ModelInfo | None]+++ class _CallKwargs(TypedDict, total=False):+ litellm_params: ReadOnly[_LitellmParams | None]+++ class _DeploymentModelInfo(TypedDict):+ id: ReadOnly[str | int]+++ class _Deployment(TypedDict):+ model_info: ReadOnly[_DeploymentModelInfo]+++ _CALL_KWARGS: Final = TypeAdapter(_CallKwargs)+ _DEPLOYMENTS: Final = TypeAdapter(list[_Deployment])+ _MEMORY_COUNTS: Final = TypeAdapter(tuple[float | None, ...] | None)+++ def _request_count_key(model_group: str, deployment_id: str) -> str:+ return f"{model_group}_request_count:{deployment_id}"+++ def _deployment_ref(kwargs: Mapping[str, object]) -> tuple[str, str] | None:++ if is_batch_retrieve_call_type(kwargs.get("call_type")):++ return None+ try:+ call: Final = _CALL_KWARGS.validate_python(kwargs)+ except ValidationError:+ return None+ litellm_params: Final = call.get("litellm_params")+ metadata: Final = litellm_params.get("metadata") if litellm_params else None+ model_info: Final = litellm_params.get("model_info") if litellm_params else None+ model_group: Final = metadata.get("model_group") if metadata else None+ deployment_id: Final = model_info.get("id") if model_info else None+ if model_group is None or deployment_id is None:+ return None+ return model_group, str(deployment_id)+++ def _request_count_keys(model_group: str, healthy_deployments: Sequence[Mapping[str, object]]) -> tuple[str, ...]:+ return tuple(+ _request_count_key(model_group, str(deployment["model_info"]["id"]))+ for deployment in _DEPLOYMENTS.validate_python(healthy_deployments)+ )+++ def _as_counts(values: Sequence[float | None]) -> tuple[int, ...]:+ return tuple(0 if value is None else int(value) for value in values)+++ def _local_counts(raw: object, keys: tuple[str, ...]) -> tuple[int, ...]:+ values: Final = _MEMORY_COUNTS.validate_python(raw)+ if values is None or len(values) != len(keys):+ return (0,) * len(keys)+ return _as_counts(values)+++ def _least_busy(+ healthy_deployments: Sequence[Mapping[str, object]], counts: tuple[int, ...]+ ) -> Mapping[str, object] | None:+ if not healthy_deployments:+ return None+ return healthy_deployments[min(range(len(healthy_deployments)), key=lambda index: counts[index])]+++ def _warn_unreadable(model_group: str, error: Exception) -> None:+ log_redis_failure(+ verbose_router_logger,+ logging.WARNING,+ f"least-busy routing could not read the shared in-flight counts for {model_group}, "+ "falling back to this worker's own counts",+ error,+ )+++ def _warn_unwritable(key: str, error: Exception) -> None:+ log_redis_failure(+ verbose_router_logger,+ logging.WARNING,+ f"least-busy routing could not update the in-flight count under {key}",+ error,+ )+class LeastBusyLoggingHandler(CustomLogger):test_flag: bool = False