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 remote-tracking branch 'origin' into litellm_ui_model_test_connection_fix
yuneng-jiangc5e25a172879
diff --cc tests/test_litellm/proxy/health_endpoints/test_health_endpoints.pyindex 594a92b0dc7,0127be8e7a7..23b3b0287ee--- a/tests/test_litellm/proxy/health_endpoints/test_health_endpoints.py+++ b/tests/test_litellm/proxy/health_endpoints/test_health_endpoints.py@@@ -17,9 -14,11 +14,12 @@@ from litellm.proxy.health_endpoints._he_db_health_readiness_check,db_health_cache,health_services_endpoint,+ test_model_connection as health_test_model_connection,)+ # Import shared proxy test helpers from conftest+ from tests.test_litellm.proxy.conftest import create_proxy_test_client+@pytest.mark.asyncio@pytest.mark.parametrize(@@@ -128,119 -127,133 +128,250 @@@ async def test_health_services_endpointmock_instance.async_health_check.assert_awaited_once()+async def test_test_model_connection_loads_config_from_router():+ """+ Test that /health/test_connection automatically loads model configuration+ (including resolved environment variables) from the router when model name is provided.+ """+ # Mock request+ mock_request = MagicMock()++ # Mock user_api_key_dict+ mock_user_api_key_dict = MagicMock()+ mock_user_api_key_dict.user_id = "test-user"+ mock_user_api_key_dict.token = "test-token"++ # Mock prisma_client+ mock_prisma_client = MagicMock()++ # Mock router with model configuration+ mock_router = MagicMock()+ mock_deployment = {+ "model_name": "gpt-4o",+ "litellm_params": {+ "model": "azure/gpt-4o",+ "api_key": "resolved-api-key-from-env",+ "api_base": "https://resolved-endpoint.openai.azure.com/",+ "api_version": "2024-10-21",+ },+ "model_info": {},+ }+ mock_router.get_model_list.return_value = [mock_deployment]++ # Mock ModelManagementAuthChecks - patch at the source module since it's imported inside the function+ mock_can_user_make_model_call = AsyncMock()++ # Mock litellm.ahealth_check+ mock_health_check_result = {+ "status": "healthy",+ "response_time_ms": 100,+ }+ mock_ahealth_check = AsyncMock(return_value=mock_health_check_result)++ # Mock run_with_timeout+ mock_run_with_timeout = AsyncMock(return_value=mock_health_check_result)++ # Mock _update_litellm_params_for_health_check+ def mock_update_params(model_info, litellm_params):+ # Just return params with messages added+ params = litellm_params.copy()+ params["messages"] = [{"role": "user", "content": "test"}]+ return params++ # Mock _resolve_os_environ_variables+ def mock_resolve_os_environ(params):+ return params++ with patch(+ "litellm.proxy.proxy_server.prisma_client",+ mock_prisma_client,+ ), patch(+ "litellm.proxy.proxy_server.llm_router",+ mock_router,+ ), patch(+ "litellm.proxy.proxy_server.premium_user",+ False,+ ), patch(+ "litellm.proxy.management_endpoints.model_management_endpoints.ModelManagementAuthChecks.can_user_make_model_call",+ mock_can_user_make_model_call,+ ), patch(+ "litellm.proxy.health_endpoints._health_endpoints.litellm.ahealth_check",+ mock_ahealth_check,+ ), patch(+ "litellm.proxy.health_endpoints._health_endpoints.run_with_timeout",+ mock_run_with_timeout,+ ), patch(+ "litellm.proxy.health_endpoints._health_endpoints._update_litellm_params_for_health_check",+ mock_update_params,+ ), patch(+ "litellm.proxy.health_endpoints._health_endpoints._resolve_os_environ_variables",+ mock_resolve_os_environ,+ ):+ # Call the endpoint with only model name (no credentials)+ result = await health_test_model_connection(+ request=mock_request,+ mode="chat",+ litellm_params={"model": "gpt-4o"},+ model_info={},+ user_api_key_dict=mock_user_api_key_dict,+ )++ # Verify router.get_model_list was called with the model name+ mock_router.get_model_list.assert_called_once_with(model_name="gpt-4o")++ # Verify that run_with_timeout was called (which wraps ahealth_check)+ assert mock_run_with_timeout.called++ # Get the call args to verify merged params+ call_args = mock_run_with_timeout.call_args+ assert call_args is not None++ # The first arg should be the coroutine from ahealth_check+ # We need to check what was passed to ahealth_check+ ahealth_check_call_args = mock_ahealth_check.call_args+ assert ahealth_check_call_args is not None+ model_params = ahealth_check_call_args.kwargs.get("model_params", {})++ # Verify that config params were loaded and merged+ # Note: request params override config params, so model from request is used+ assert model_params.get("api_key") == "resolved-api-key-from-env"+ assert model_params.get("api_base") == "https://resolved-endpoint.openai.azure.com/"+ assert model_params.get("api_version") == "2024-10-21"+ assert model_params.get("model") == "gpt-4o" # Request param overrides config param++ # Verify result+ assert result["status"] == "success"+ assert "result" in result++++ @pytest.fixture(scope="function")+ def proxy_client(monkeypatch):+ """+ Fixture that starts a proxy server instance for testing.+ Uses the actual FastAPI app from proxy_server which includes all routers.++ Note: TestClient doesn't start a real HTTP server - it runs the FastAPI app+ in-process. However, it DOES trigger FastAPI's lifespan events (startup/shutdown)+ when used as a context manager, which initializes the proxy server components.++ Database access:+ - If DATABASE_URL is set in environment, the proxy will automatically connect+ - Database connection happens during lifespan startup events+ - To enable database access, set DATABASE_URL environment variable before running tests++ Redis cache:+ - If REDIS_HOST is set in environment, Redis cache will be automatically configured+ - Cache configuration is included in /health/readiness endpoint response+ """+ client = create_proxy_test_client(monkeypatch)+ with client:+ yield client+++ def test_health_liveliness_endpoint(proxy_client):+ """+ Test that /health/liveliness endpoint returns 200 OK with "I'm alive!" message.+ This is a critical orchestration endpoint that must be simple and fast.+ """+ # Measure the time taken for the health check call+ start_time = time.perf_counter()++ # Make GET request to /health/liveliness+ response = proxy_client.get("/health/liveliness")++ end_time = time.perf_counter()+ duration_ms = (end_time - start_time) * 1000++ # Assert response status+ assert response.status_code == 200, f"Expected 200 OK, got {response.status_code}: {response.text}"++ # Assert response content (FastAPI JSON-encodes the string)+ assert response.json() == "I'm alive!", f"Expected 'I'm alive!' message, got: {response.json()}"++ # Verify response is fast (should be < 100ms for a simple endpoint)+ # This is critical for orchestration systems that poll frequently+ assert duration_ms < 100, f"Health check took {duration_ms:.2f}ms, expected < 100ms for a simple endpoint"++ # Log the duration for visibility (useful for CI/CD monitoring)+ print(f"\n/health/liveliness response time: {duration_ms:.2f}ms")+++ def test_health_liveness_endpoint(proxy_client):+ """+ Test that /health/liveness endpoint (Kubernetes standard name) also works.+ """+ # Measure the time taken for the health check call+ start_time = time.perf_counter()++ # Make GET request to /health/liveness+ response = proxy_client.get("/health/liveness")++ end_time = time.perf_counter()+ duration_ms = (end_time - start_time) * 1000++ # Assert response status+ assert response.status_code == 200, f"Expected 200 OK, got {response.status_code}: {response.text}"++ # Assert response content (FastAPI JSON-encodes the string)+ assert response.json() == "I'm alive!", f"Expected 'I'm alive!' message, got: {response.json()}"++ # Verify response is fast (should be < 100ms for a simple endpoint)+ assert duration_ms < 100, f"Health check took {duration_ms:.2f}ms, expected < 100ms for a simple endpoint"++ # Log the duration for visibility (useful for CI/CD monitoring)+ print(f"\n/health/liveness response time: {duration_ms:.2f}ms")+++ def test_health_readiness(proxy_client):+ """+ Test /health/readiness endpoint.+ Database and Redis are optional - the endpoint should work whether they're available or not.++ If DATABASE_URL is set, the endpoint will check database connectivity.+ If REDIS_HOST is set, the endpoint will report cache status.+ If neither is set, the endpoint should still return a valid health status.+ """+ # Measure the time taken for the health check call+ start_time = time.perf_counter()++ # Make GET request to /health/readiness+ response = proxy_client.get("/health/readiness")++ end_time = time.perf_counter()+ duration_ms = (end_time - start_time) * 1000++ # Assert response status+ assert response.status_code == 200, f"Expected 200 OK, got {response.status_code}: {response.text}"++ # Verify response is fast (readiness may include DB check if available, so < 500ms is reasonable)+ # This is critical for orchestration systems (Kubernetes) that poll frequently+ assert duration_ms < 500, f"Health check took {duration_ms:.2f}ms, expected < 500ms for readiness endpoint"++ # Assert response contains expected fields+ response_data = response.json()+ assert "status" in response_data, "Response should contain 'status' field"+ assert "litellm_version" in response_data, "Response should contain 'litellm_version' field"++ # Display all health endpoint response fields (matches what /health/readiness returns)+ print("\n" + "-"*60)+ print("HEALTH ENDPOINT RESPONSE")+ print("-"*60)+ print(f"Status: {response_data.get('status', 'unknown')}")+ print(f"Database: {response_data.get('db', 'not reported')}")+ print(f"LiteLLM Version: {response_data.get('litellm_version', 'unknown')}")+ print(f"Success Callbacks: {response_data.get('success_callbacks', [])}")+ print(f"Cache: {response_data.get('cache', 'none')}")+ print(f"Use AioHTTP Transport: {response_data.get('use_aiohttp_transport', 'unknown')}")+ print(f"Response time: {duration_ms:.2f}ms")++ # If database status is reported, verify it's a valid status+ # Database may be "connected", "disconnected", "unknown", or "Not connected" (when prisma_client is None)+ if "db" in response_data:+ db_status = response_data["db"]+ # Database status can be any of these valid states+ assert db_status in ["connected", "disconnected", "unknown", "Not connected"], \+ f"Unexpected db status: {db_status}"++ print("="*60 + "\n")+