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
refactor: extract should_use_polling_for_request to polling_handler module
Xianzong Xie5d59f47db476
diff --git a/litellm/proxy/response_api_endpoints/endpoints.py b/litellm/proxy/response_api_endpoints/endpoints.pyindex 3956d081f4b..d94bce3bea2 100644--- a/litellm/proxy/response_api_endpoints/endpoints.py+++ b/litellm/proxy/response_api_endpoints/endpoints.py@@ -79,55 +79,18 @@ async def responses_api(data = await _read_request_body(request=request)- # Check if polling via cache is enabled (using global config vars)- background_mode = data.get("background", False)+ # Check if polling via cache should be used for this request+ from litellm.proxy.response_polling.polling_handler import should_use_polling_for_request- # Check if polling is enabled (can be "all" or a list of providers)- should_use_polling = False- if background_mode and polling_via_cache_enabled and redis_usage_cache:- if polling_via_cache_enabled == "all":- # Enable for all models/providers- should_use_polling = True- elif isinstance(polling_via_cache_enabled, list):- # Check if provider is in the list (e.g., ["openai", "bedrock"])- model = data.get("model", "")-- # First, try to get provider from model string format "provider/model"- if "/" in model:- provider = model.split("/")[0]- if provider in polling_via_cache_enabled:- should_use_polling = True- # Otherwise, check ALL deployments for this model_name in router- elif llm_router is not None:- try:- # Get all deployment indices for this model name- indices = llm_router.model_name_to_deployment_indices.get(model, [])- for idx in indices:- deployment_dict = llm_router.model_list[idx]- litellm_params = deployment_dict.get("litellm_params", {})-- # Check custom_llm_provider first- dep_provider = litellm_params.get("custom_llm_provider")-- # Then try to extract from model (e.g., "openai/gpt-5")- if not dep_provider:- dep_model = litellm_params.get("model", "")- if "/" in dep_model:- dep_provider = dep_model.split("/")[0]-- # If ANY deployment's provider matches, enable polling- if dep_provider and dep_provider in polling_via_cache_enabled:- should_use_polling = True- verbose_proxy_logger.debug(- f"Polling enabled for model={model}, provider={dep_provider}"- )- break- except Exception as e:- verbose_proxy_logger.debug(- f"Could not resolve provider for model {model}: {e}"- )+ should_use_polling = should_use_polling_for_request(+ background_mode=data.get("background", False),+ polling_via_cache_enabled=polling_via_cache_enabled,+ redis_cache=redis_usage_cache,+ model=data.get("model", ""),+ llm_router=llm_router,+ )- # If all conditions are met, use polling mode+ # If polling is enabled, use polling modeif should_use_polling:from litellm.proxy.response_polling.polling_handler import (ResponsePollingHandler,diff --git a/litellm/proxy/response_polling/__init__.py b/litellm/proxy/response_polling/__init__.pyindex b014286b9ef..b500354c373 100644--- a/litellm/proxy/response_polling/__init__.py+++ b/litellm/proxy/response_polling/__init__.py@@ -4,9 +4,13 @@ Response Polling Module for Background Responses with Cachefrom litellm.proxy.response_polling.background_streaming import (background_streaming_task,)-from litellm.proxy.response_polling.polling_handler import ResponsePollingHandler+from litellm.proxy.response_polling.polling_handler import (+ ResponsePollingHandler,+ should_use_polling_for_request,+)__all__ = ["ResponsePollingHandler","background_streaming_task",+ "should_use_polling_for_request",]diff --git a/litellm/proxy/response_polling/polling_handler.py b/litellm/proxy/response_polling/polling_handler.pyindex 650846663e7..121b128f06d 100644--- a/litellm/proxy/response_polling/polling_handler.py+++ b/litellm/proxy/response_polling/polling_handler.py@@ -255,3 +255,69 @@ class ResponsePollingHandler:return False+def should_use_polling_for_request(+ background_mode: bool,+ polling_via_cache_enabled, # Can be False, "all", or List[str]+ redis_cache, # RedisCache or None+ model: str,+ llm_router, # Router instance or None+) -> bool:+ """+ Determine if polling via cache should be used for a request.++ Args:+ background_mode: Whether background=true was set in the request+ polling_via_cache_enabled: Config value - False, "all", or list of providers+ redis_cache: Redis cache instance (required for polling)+ model: Model name from the request (e.g., "gpt-5" or "openai/gpt-4o")+ llm_router: LiteLLM router instance for looking up model deployments++ Returns:+ True if polling should be used, False otherwise+ """+ # All conditions must be met+ if not (background_mode and polling_via_cache_enabled and redis_cache):+ return False++ # "all" enables polling for all providers+ if polling_via_cache_enabled == "all":+ return True++ # Check if provider is in the enabled list+ if isinstance(polling_via_cache_enabled, list):+ # First, try to get provider from model string format "provider/model"+ if "/" in model:+ provider = model.split("/")[0]+ if provider in polling_via_cache_enabled:+ return True+ # Otherwise, check ALL deployments for this model_name in router+ elif llm_router is not None:+ try:+ # Get all deployment indices for this model name+ indices = llm_router.model_name_to_deployment_indices.get(model, [])+ for idx in indices:+ deployment_dict = llm_router.model_list[idx]+ litellm_params = deployment_dict.get("litellm_params", {})++ # Check custom_llm_provider first+ dep_provider = litellm_params.get("custom_llm_provider")++ # Then try to extract from model (e.g., "openai/gpt-5")+ if not dep_provider:+ dep_model = litellm_params.get("model", "")+ if "/" in dep_model:+ dep_provider = dep_model.split("/")[0]++ # If ANY deployment's provider matches, enable polling+ if dep_provider and dep_provider in polling_via_cache_enabled:+ verbose_proxy_logger.debug(+ f"Polling enabled for model={model}, provider={dep_provider}"+ )+ return True+ except Exception as e:+ verbose_proxy_logger.debug(+ f"Could not resolve provider for model {model}: {e}"+ )++ return False+diff --git a/tests/proxy_unit_tests/test_response_polling_handler.py b/tests/proxy_unit_tests/test_response_polling_handler.pyindex f72df3a11b4..5d9b83969f7 100644--- a/tests/proxy_unit_tests/test_response_polling_handler.py+++ b/tests/proxy_unit_tests/test_response_polling_handler.py@@ -864,98 +864,139 @@ class TestProviderResolutionForPolling:class TestPollingConditionChecks:"""Test cases for the conditions that determine whether polling should be enabled.- Tests the logic in endpoints.py responses_api function.+ Tests the should_use_polling_for_request function."""def test_polling_enabled_when_all_conditions_met(self):"""Test polling is enabled when background=true, polling_via_cache="all", and redis is available"""- background_mode = True- polling_via_cache_enabled = "all"- redis_usage_cache = Mock() # Non-None mock+ from litellm.proxy.response_polling.polling_handler import should_use_polling_for_request- should_use_polling = False- if background_mode and polling_via_cache_enabled and redis_usage_cache:- if polling_via_cache_enabled == "all":- should_use_polling = True+ result = should_use_polling_for_request(+ background_mode=True,+ polling_via_cache_enabled="all",+ redis_cache=Mock(),+ model="gpt-4o",+ llm_router=None,+ )- assert should_use_polling is True+ assert result is Truedef test_polling_disabled_when_background_false(self):"""Test polling is disabled when background=false"""- background_mode = False- polling_via_cache_enabled = "all"- redis_usage_cache = Mock()+ from litellm.proxy.response_polling.polling_handler import should_use_polling_for_request- should_use_polling = False- if background_mode and polling_via_cache_enabled and redis_usage_cache:- if polling_via_cache_enabled == "all":- should_use_polling = True+ result = should_use_polling_for_request(+ background_mode=False,+ polling_via_cache_enabled="all",+ redis_cache=Mock(),+ model="gpt-4o",+ llm_router=None,+ )- assert should_use_polling is False+ assert result is Falsedef test_polling_disabled_when_config_false(self):"""Test polling is disabled when polling_via_cache is False"""- background_mode = True- polling_via_cache_enabled = False- redis_usage_cache = Mock()+ from litellm.proxy.response_polling.polling_handler import should_use_polling_for_request- should_use_polling = False- if background_mode and polling_via_cache_enabled and redis_usage_cache:- if polling_via_cache_enabled == "all":- should_use_polling = True+ result = should_use_polling_for_request(+ background_mode=True,+ polling_via_cache_enabled=False,+ redis_cache=Mock(),+ model="gpt-4o",+ llm_router=None,+ )- assert should_use_polling is False+ assert result is Falsedef test_polling_disabled_when_redis_not_configured(self):"""Test polling is disabled when Redis is not configured"""- background_mode = True- polling_via_cache_enabled = "all"- redis_usage_cache = None+ from litellm.proxy.response_polling.polling_handler import should_use_polling_for_request- should_use_polling = False- if background_mode and polling_via_cache_enabled and redis_usage_cache:- if polling_via_cache_enabled == "all":- should_use_polling = True+ result = should_use_polling_for_request(+ background_mode=True,+ polling_via_cache_enabled="all",+ redis_cache=None,+ model="gpt-4o",+ llm_router=None,+ )- assert should_use_polling is False+ assert result is Falsedef test_polling_enabled_with_provider_list_match(self):"""Test polling is enabled when provider list matches"""- background_mode = True- polling_via_cache_enabled = ["openai", "anthropic"]- redis_usage_cache = Mock()- model = "openai/gpt-4o"-- should_use_polling = False- if background_mode and polling_via_cache_enabled and redis_usage_cache:- if polling_via_cache_enabled == "all":- should_use_polling = True- elif isinstance(polling_via_cache_enabled, list):- if "/" in model:- provider = model.split("/")[0]- if provider in polling_via_cache_enabled:- should_use_polling = True+ from litellm.proxy.response_polling.polling_handler import should_use_polling_for_request++ result = should_use_polling_for_request(+ background_mode=True,+ polling_via_cache_enabled=["openai", "anthropic"],+ redis_cache=Mock(),+ model="openai/gpt-4o",+ llm_router=None,+ )- assert should_use_polling is True+ assert result is Truedef test_polling_disabled_with_provider_list_no_match(self):"""Test polling is disabled when provider not in list"""- background_mode = True- polling_via_cache_enabled = ["openai"]- redis_usage_cache = Mock()- model = "anthropic/claude-3"+ from litellm.proxy.response_polling.polling_handler import should_use_polling_for_request++ result = should_use_polling_for_request(+ background_mode=True,+ polling_via_cache_enabled=["openai"],+ redis_cache=Mock(),+ model="anthropic/claude-3",+ llm_router=None,+ )- should_use_polling = False- if background_mode and polling_via_cache_enabled and redis_usage_cache:- if polling_via_cache_enabled == "all":- should_use_polling = True- elif isinstance(polling_via_cache_enabled, list):- if "/" in model:- provider = model.split("/")[0]- if provider in polling_via_cache_enabled:- should_use_polling = True+ assert result is False++ def test_polling_with_router_lookup(self):+ """Test polling uses router to resolve model name to provider"""+ from litellm.proxy.response_polling.polling_handler import should_use_polling_for_request- assert should_use_polling is False+ # Create mock router+ mock_router = Mock()+ mock_router.model_name_to_deployment_indices = {"gpt-5": [0]}+ mock_router.model_list = [+ {+ "model_name": "gpt-5",+ "litellm_params": {"model": "openai/gpt-5"}+ }+ ]++ result = should_use_polling_for_request(+ background_mode=True,+ polling_via_cache_enabled=["openai"],+ redis_cache=Mock(),+ model="gpt-5", # No slash, needs router lookup+ llm_router=mock_router,+ )++ assert result is True++ def test_polling_with_router_lookup_no_match(self):+ """Test polling returns False when router lookup finds non-matching provider"""+ from litellm.proxy.response_polling.polling_handler import should_use_polling_for_request++ mock_router = Mock()+ mock_router.model_name_to_deployment_indices = {"claude-3": [0]}+ mock_router.model_list = [+ {+ "model_name": "claude-3",+ "litellm_params": {"model": "anthropic/claude-3-sonnet"}+ }+ ]++ result = should_use_polling_for_request(+ background_mode=True,+ polling_via_cache_enabled=["openai"],+ redis_cache=Mock(),+ model="claude-3",+ llm_router=mock_router,+ )++ assert result is Falseclass TestStreamingEventParsing: