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
Merge origin/main; keep both model_group_info and access_groups cache invalidation
Ryan Crabbeba0f79459181
diff --cc litellm/router.pyindex 5b72c3fb669,46d35352c37..3a6c514989d--- a/litellm/router.py+++ b/litellm/router.py@@@ -6055,7 -6423,7 +6423,8 @@@ class Routerself.model_list = []self.model_id_to_deployment_index_map = {} # Reset the indexself.model_name_to_deployment_indices = {} # Reset the model_name index+ self._invalidate_model_group_info_cache()+ self._invalidate_access_groups_cache()# we add api_base/api_key each model so load balancing between azure/gpt on api_base1 and api_base2 worksfor model in original_model_list:@@@ -6359,7 -6733,7 +6734,8 @@@"""idx = len(self.model_list)self.model_list.append(model)+ self._invalidate_model_group_info_cache()+ self._invalidate_access_groups_cache()# Update model_id index for O(1) lookupif model_id is not None:@@@ -6407,7 -6781,7 +6783,8 @@@if removal_idx is not None:self.model_list.pop(removal_idx)+ self._invalidate_model_group_info_cache()+ self._invalidate_access_groups_cache()self._update_deployment_indices_after_removal(model_id=deployment_id, removal_idx=removal_idx)@@@ -6441,7 -6815,7 +6818,8 @@@if deployment_idx is not None:# Pop the item from the list firstitem = self.model_list.pop(deployment_idx)+ self._invalidate_model_group_info_cache()+ self._invalidate_access_groups_cache()self._update_deployment_indices_after_removal(model_id=id, removal_idx=deployment_idx)@@@ -7176,7 -7576,7 +7580,8 @@@"""# First populate the model_listself.model_list = []+ self._invalidate_model_group_info_cache()+ self._invalidate_access_groups_cache()for _, model in enumerate(model_list):# Extract model_info from the model dictmodel_info = model.get("model_info", {})@@@ -7513,13 -7920,13 +7925,20 @@@return returned_models+ def _invalidate_model_group_info_cache(self) -> None:+ """Invalidate the cached model group info.++ Call this whenever self.model_list is modified to ensure the cache is rebuilt.+ """+ self._cached_get_model_group_info.cache_clear()++ def _invalidate_access_groups_cache(self) -> None:+ """Invalidate the cached access groups.++ Call this whenever self.model_list is modified to ensure the cache is rebuilt.+ """+ self._access_groups_cache = None+def get_model_access_groups(self,model_name: Optional[str] = None,diff --cc tests/test_litellm/test_router.pyindex 48aa435c3a9,5732deda6fb..4bb9685f5e6--- a/tests/test_litellm/test_router.py+++ b/tests/test_litellm/test_router.py@@@ -925,73 -925,132 +925,199 @@@ def test_router_get_model_access_groupsassert list(access_groups.keys()) == ["default-models"]+def test_cached_get_model_group_info():+ """+ Test that _cached_get_model_group_info caches results and+ invalidates on deployment changes.+ """+ from litellm.types.router import Deployment, LiteLLM_Params++ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-4",+ "litellm_params": {"model": "gpt-4", "api_key": "fake"},+ "model_info": {"tpm": 1000, "rpm": 100},+ },+ ]+ )++ # First call should compute and cache+ result1 = router._cached_get_model_group_info("gpt-4")+ assert result1 is not None+ assert result1.tpm == 1000++ # Second call should hit cache (same object)+ result2 = router._cached_get_model_group_info("gpt-4")+ assert result1 is result2++ # Add a deployment — cache should be invalidated+ router.add_deployment(+ Deployment(+ model_name="gpt-4",+ litellm_params=LiteLLM_Params(model="gpt-4", api_key="fake2"),+ model_info={"tpm": 2000, "rpm": 200},+ )+ )+ result3 = router._cached_get_model_group_info("gpt-4")+ assert result3 is not result2+ assert result3 is not None+ assert result3.tpm == 3000 # 1000 + 2000++ # Delete a deployment — cache should be invalidated+ deployment_id = router.model_list[-1]["model_info"]["id"]+ router.delete_deployment(id=deployment_id)+ result4 = router._cached_get_model_group_info("gpt-4")+ assert result4 is not result3+ assert result4 is not None+ assert result4.tpm == 1000++ # set_model_list — cache should be invalidated+ router.set_model_list(+ [+ {+ "model_name": "gpt-4",+ "litellm_params": {"model": "gpt-4", "api_key": "fake"},+ "model_info": {"tpm": 5000},+ },+ ]+ )+ result5 = router._cached_get_model_group_info("gpt-4")+ assert result5 is not result4+ assert result5 is not None+ assert result5.tpm == 5000++ # Verify cache still works after invalidation+ result6 = router._cached_get_model_group_info("gpt-4")+ assert result5 is result6+++ def test_get_model_access_groups_caching():+ """+ Test that get_model_access_groups caches the no-args result+ and invalidates on deployment changes.+ """+ from litellm.types.router import Deployment, LiteLLM_Params++ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-4",+ "litellm_params": {"model": "gpt-4"},+ "model_info": {"access_groups": ["premium"]},+ },+ ]+ )++ # First call computes and populates cache+ result1 = router.get_model_access_groups()+ assert "premium" in result1++ # All subsequent calls should return the same cached object (including first)+ result2 = router.get_model_access_groups()+ assert result1 is result2++ # Calls with args should bypass cache+ result_with_args = router.get_model_access_groups(model_name="gpt-4")+ assert result_with_args is not result2++ # Add a deployment — cache should be invalidated+ router.add_deployment(+ Deployment(+ model_name="gpt-3.5",+ litellm_params=LiteLLM_Params(model="gpt-3.5-turbo"),+ model_info={"access_groups": ["default"]},+ )+ )+ result3 = router.get_model_access_groups()+ assert result3 is not result2+ assert "premium" in result3+ assert "default" in result3++ # Delete the deployment — cache should be invalidated again+ deployment_id = None+ for m in router.model_list:+ if m.get("model_name") == "gpt-3.5":+ deployment_id = m.get("model_info", {}).get("id")+ break+ assert deployment_id is not None+ router.delete_deployment(id=deployment_id)+ result4 = router.get_model_access_groups()+ assert result4 is not result3+ assert "default" not in result4+ assert "premium" in result4+++ def test_get_model_access_groups_cache_invalidation_set_model_list():+ """+ Test that set_model_list invalidates the access groups cache.+ """+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-4",+ "litellm_params": {"model": "gpt-4"},+ "model_info": {"access_groups": ["premium"]},+ },+ ]+ )++ # Populate cache+ result1 = router.get_model_access_groups()+ assert "premium" in result1++ # set_model_list should invalidate cache+ router.set_model_list(+ [+ {+ "model_name": "claude-3",+ "litellm_params": {"model": "anthropic/claude-3-opus-20240229"},+ "model_info": {"access_groups": ["research"]},+ },+ ]+ )+ result2 = router.get_model_access_groups()+ assert result2 is not result1+ assert "research" in result2+ assert "premium" not in result2+++ def test_get_model_access_groups_cache_invalidation_upsert_deployment():+ """+ Test that upsert_deployment invalidates the access groups cache.+ """+ from litellm.types.router import Deployment, LiteLLM_Params++ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-4",+ "litellm_params": {"model": "gpt-4"},+ "model_info": {"access_groups": ["premium"]},+ },+ ]+ )++ # Populate cache+ result1 = router.get_model_access_groups()+ assert "premium" in result1++ # Get the existing deployment's ID+ existing_id = router.model_list[0]["model_info"]["id"]++ # Upsert with the same ID but different params — triggers pop + re-add+ router.upsert_deployment(+ Deployment(+ model_name="gpt-4-updated",+ litellm_params=LiteLLM_Params(model="gpt-4-turbo"),+ model_info={"id": existing_id, "access_groups": ["updated-group"]},+ )+ )+ result2 = router.get_model_access_groups()+ assert result2 is not result1+ assert "updated-group" in result2++@pytest.mark.asyncioasync def test_acompletion_streaming_iterator():"""Test _acompletion_streaming_iterator for normal streaming and fallback behavior."""