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(router): treat a routing entry with no latency samples as zero latency
mateo-berric55248d11380
diff --git a/litellm/router_strategy/lowest_latency.py b/litellm/router_strategy/lowest_latency.pyindex a1b67eaeaf9..4a1fb4f325a 100644--- a/litellm/router_strategy/lowest_latency.py+++ b/litellm/router_strategy/lowest_latency.py@@ -1,6 +1,7 @@#### What this does ##### picks based on response time (for streaming, this is time to first token)import random+from collections.abc import Sequencefrom datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Any, Final@@ -25,6 +26,12 @@ class RoutingArgs(LiteLLMPydanticObjectBase):max_latency_list_size: int = 10+def _average_latency(samples: Sequence[float | int]) -> float:+ if not samples:+ return 0.0+ return sum(sample for sample in samples if isinstance(sample, float)) / len(samples)++class LowestLatencyLoggingHandler(CustomLogger):test_flag: bool = Falselogged_success: int = 0@@ -431,23 +438,13 @@ class LowestLatencyLoggingHandler(CustomLogger):item_tpm = item_map.get(precise_minute, {}).get("tpm", 0)# get average latency or average ttft (depending on streaming/non-streaming)- total: float = 0.0use_ttft = (request_kwargs is not Noneand request_kwargs.get("stream", None) is not Noneand request_kwargs["stream"] is Trueand len(item_ttft_latency) > 0)- if use_ttft:- for _call_latency in item_ttft_latency:- if isinstance(_call_latency, float):- total += _call_latency- item_latency = total / len(item_ttft_latency)- else:- for _call_latency in item_latency:- if isinstance(_call_latency, float):- total += _call_latency- item_latency = total / len(item_latency)+ average_latency = _average_latency(item_ttft_latency if use_ttft else item_latency)# -------------- ## Debugging Logic@@ -456,7 +453,7 @@ class LowestLatencyLoggingHandler(CustomLogger):# 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] = item_latency+ _latency_per_deployment[_deployment_api_base] = average_latency# -------------- ## End of Debugging Logic# -------------- #@@ -466,7 +463,7 @@ class LowestLatencyLoggingHandler(CustomLogger):): # if user passed in tpm / rpm in the model_listcontinueelse:- potential_deployments.append((_deployment, item_latency))+ potential_deployments.append((_deployment, average_latency))if len(potential_deployments) == 0:return Nonediff --git a/tests/test_litellm/router_strategy/test_lowest_latency.py b/tests/test_litellm/router_strategy/test_lowest_latency.pyindex 6701f4a7aa2..251b760a8d8 100644--- a/tests/test_litellm/router_strategy/test_lowest_latency.py+++ b/tests/test_litellm/router_strategy/test_lowest_latency.py@@ -163,3 +163,33 @@ def test_sync_chat_zero_completion_tokens_falls_back_to_seconds():assert latencies and latencies[-1] == pytest.approx(2.0)assert not isinstance(latencies[-1], timedelta)json.dumps({"latency": latencies})+++ "cached_entry",+ [{"latency": []}, {"2026-09-05-15-39": {"tpm": 28, "rpm": 1}}],+ ids=["empty_latency_list", "minute_bucket_only_as_cost_based_routing_writes"],+)+async def test_async_get_available_deployments_treats_missing_samples_as_zero_latency(cached_entry):+ """A cached entry with no latency samples (cost-based routing shares the group's map key and writes+ minute buckets only) must count as 0 latency, like an unseen deployment, instead of dividing by zero."""+ cache = DualCache()+ handler = LowestLatencyLoggingHandler(router_cache=cache)+ cache.set_cache(+ key="gemini-embedding-001_map",+ value={DEPLOYMENT_ID: cached_entry, "slower": {"latency": [0.5]}},+ )+ healthy_deployments = [+ {"model_info": {"id": DEPLOYMENT_ID}, "litellm_params": {}},+ {"model_info": {"id": "slower"}, "litellm_params": {}},+ ]++ picked = await handler.async_get_available_deployments(+ model_group="gemini-embedding-001",+ healthy_deployments=healthy_deployments,+ request_kwargs={"stream": False, "metadata": {}},+ )++ assert picked is not None+ assert picked["model_info"]["id"] == DEPLOYMENT_ID