|
| 1 | +import uuid |
| 2 | +import requests |
| 3 | +from typing import Optional |
| 4 | +from azure.ai.ml import MLClient |
| 5 | +from azure.ai.ml.entities import ( |
| 6 | + EndpointAuthKeys, |
| 7 | + ManagedOnlineEndpoint, |
| 8 | + ManagedOnlineDeployment, |
| 9 | + KubernetesOnlineEndpoint, |
| 10 | + KubernetesOnlineDeployment, |
| 11 | + ProbeSettings, |
| 12 | + OnlineRequestSettings, |
| 13 | +) |
| 14 | + |
| 15 | + |
| 16 | +def get_default_probe_settings() -> ProbeSettings: |
| 17 | + """Get default probe settings for deployments.""" |
| 18 | + return ProbeSettings( # Probes are APIs exposed by the deployment which informs the frameworktraffic |
| 19 | + initial_delay=1400, # if the deployment is healthy and ready to receive |
| 20 | + period=30, |
| 21 | + timeout=2, |
| 22 | + success_threshold=1, |
| 23 | + failure_threshold=30 |
| 24 | + ) |
| 25 | + |
| 26 | + |
| 27 | +def get_default_request_settings() -> OnlineRequestSettings: |
| 28 | + """Get default request settings for deployments.""" |
| 29 | + return OnlineRequestSettings( # Online request setting which controls timeout and concurrent request per instance |
| 30 | + request_timeout_ms=90000, |
| 31 | + max_concurrent_requests_per_instance=4, |
| 32 | + ) |
| 33 | + |
| 34 | + |
| 35 | +def create_managed_deployment( |
| 36 | + ml_client: MLClient, |
| 37 | + model_asset_id: str, # Asset ID of the model to deploy |
| 38 | + instance_type: str, # Supported instance type for managed deployment |
| 39 | + environment_asset_id: Optional[str] = None, # Asset ID of the serving engine to use |
| 40 | + endpoint_name: Optional[str] = None, |
| 41 | + endpoint_description: str = "Sample endpoint", |
| 42 | + endpoint_tags: dict = {}, |
| 43 | + deployment_name: Optional[str] = None, |
| 44 | + deployment_env_vars: dict = {}, |
| 45 | +) -> str: |
| 46 | + """Create a managed deployment.""" |
| 47 | + guid = str(uuid.uuid4())[:8] # Unique suffix to avoid name collisions |
| 48 | + endpoint_name = endpoint_name or f"rl-endpoint" |
| 49 | + endpoint_name = f"{endpoint_name}-{guid}" # Unique names prevent collisions and allow parallel experiments |
| 50 | + deployment_name = deployment_name or "default" |
| 51 | + |
| 52 | + endpoint = ManagedOnlineEndpoint( # Use AzureML endpoint abstraction for traffic management and auth |
| 53 | + name=endpoint_name, |
| 54 | + auth_mode="key", |
| 55 | + description=endpoint_description, |
| 56 | + tags=endpoint_tags, |
| 57 | + ) |
| 58 | + |
| 59 | + print(f"Creating endpoint: {endpoint_name}") |
| 60 | + ml_client.online_endpoints.begin_create_or_update(endpoint).wait() # Using there the endpoint object to trigger actual endpoint in AML workspace. |
| 61 | + |
| 62 | + deployment = ManagedOnlineDeployment( # Use deployment abstraction for scaling, versioning, and isolation |
| 63 | + name=deployment_name, |
| 64 | + endpoint_name=endpoint_name, |
| 65 | + model=model_asset_id, |
| 66 | + instance_type=instance_type, |
| 67 | + instance_count=1, |
| 68 | + environment=environment_asset_id, |
| 69 | + environment_variables=deployment_env_vars, |
| 70 | + liveness_probe=get_default_probe_settings(), |
| 71 | + readiness_probe=get_default_probe_settings(), |
| 72 | + request_settings=get_default_request_settings(), |
| 73 | + ) |
| 74 | + |
| 75 | + print(f"Creating deployment (15-20 min)...") # |
| 76 | + ml_client.online_deployments.begin_create_or_update(deployment).wait() |
| 77 | + |
| 78 | + # Route all traffic to new deployment for immediate use |
| 79 | + endpoint.traffic = {deployment_name: 100} |
| 80 | + ml_client.online_endpoints.begin_create_or_update(endpoint).result() |
| 81 | + |
| 82 | + print(f"Endpoint ready: {endpoint_name}") |
| 83 | + |
| 84 | + return endpoint_name |
| 85 | + |
| 86 | + |
| 87 | +def create_kubernetes_deployment( |
| 88 | + ml_client: MLClient, |
| 89 | + model_asset_id: str, # Asset ID of the model to deploy |
| 90 | + environment_asset_id: str, # Asset ID of the serving engine to use |
| 91 | + instance_type: str, # Kubernetes supports partial node usage granular upto the GPU level |
| 92 | + compute_name: str, # Name of the compute which will be use for endpoint creation |
| 93 | + endpoint_name: Optional[str] = None, |
| 94 | + endpoint_description: str = "Sample endpoint", |
| 95 | + endpoint_tags: dict = {}, |
| 96 | + deployment_name: Optional[str] = None, |
| 97 | + deployment_env_vars: dict = {}, |
| 98 | + model_mount_path: str = "/var/model-mount", |
| 99 | +) -> str: |
| 100 | + """Create endpoint using Kubernetes.""" |
| 101 | + |
| 102 | + print("🌐 Creating endpoint...") |
| 103 | + |
| 104 | + guid = str(uuid.uuid4())[:8] # Unique suffix to avoid name collisions |
| 105 | + endpoint_name = endpoint_name or f"rl-endpoint" |
| 106 | + endpoint_name = f"{endpoint_name}-{guid}" # Unique names prevent collisions and allow parallel experiments |
| 107 | + deployment_name = deployment_name or "default" |
| 108 | + |
| 109 | + endpoint = KubernetesOnlineEndpoint( # Use AzureML endpoint abstraction for traffic management and auth |
| 110 | + name=endpoint_name, |
| 111 | + auth_mode="key", |
| 112 | + compute=compute_name, |
| 113 | + description=endpoint_description, |
| 114 | + tags=endpoint_tags, |
| 115 | + ) |
| 116 | + |
| 117 | + print(f"Creating endpoint: {endpoint_name}") |
| 118 | + ml_client.online_endpoints.begin_create_or_update(endpoint).wait() # Using there the endpoint object to trigger actual endpoint in AML workspace. |
| 119 | + |
| 120 | + deployment = KubernetesOnlineDeployment( # Use deployment abstraction for scaling, versioning, and isolation |
| 121 | + name=deployment_name, |
| 122 | + endpoint_name=endpoint_name, |
| 123 | + model=model_asset_id, |
| 124 | + model_mount_path=model_mount_path, |
| 125 | + instance_type=instance_type, |
| 126 | + instance_count=1, |
| 127 | + environment=environment_asset_id, |
| 128 | + environment_variables=deployment_env_vars, |
| 129 | + liveness_probe=get_default_probe_settings(), |
| 130 | + readiness_probe=get_default_probe_settings(), |
| 131 | + request_settings=get_default_request_settings(), |
| 132 | + ) |
| 133 | + |
| 134 | + print(f"Creating deployment (15-20 min)...") # |
| 135 | + ml_client.online_deployments.begin_create_or_update(deployment).wait() |
| 136 | + |
| 137 | + # Route all traffic to new deployment for immediate use |
| 138 | + endpoint.traffic = {deployment_name: 100} |
| 139 | + ml_client.online_endpoints.begin_create_or_update(endpoint).result() |
| 140 | + |
| 141 | + print(f"Endpoint ready: {endpoint_name}") |
| 142 | + |
| 143 | + return endpoint_name |
| 144 | + |
| 145 | + |
| 146 | +def test_deployment(ml_client, endpoint_name): |
| 147 | + """Run a test request against a deployed endpoint and print the result.""" |
| 148 | + print("Testing endpoint...") |
| 149 | + # Retrieve endpoint URI and API key to authenticate test request |
| 150 | + scoring_uri = ml_client.online_endpoints.get(endpoint_name).scoring_uri |
| 151 | + if not scoring_uri: |
| 152 | + raise ValueError("Scoring URI not found for endpoint.") |
| 153 | + |
| 154 | + api_keys = ml_client.online_endpoints.get_keys(endpoint_name) |
| 155 | + if not isinstance(api_keys, EndpointAuthKeys) or not api_keys.primary_key: |
| 156 | + raise ValueError("API key not found for endpoint.") |
| 157 | + |
| 158 | + # Use a realistic financial question to verify model reasoning and output format |
| 159 | + payload = { |
| 160 | + "messages": [ |
| 161 | + { |
| 162 | + "role": "user", |
| 163 | + "content": """Please answer the following financial question: |
| 164 | +
|
| 165 | +Context: A company has revenue of $1,000,000 and expenses of $750,000. |
| 166 | +
|
| 167 | +Question: What is the profit margin as a percentage? |
| 168 | +Let's think step by step and put final answer after ####.""" |
| 169 | + } |
| 170 | + ], |
| 171 | + "max_tokens": 512, |
| 172 | + "temperature": 0.7, |
| 173 | + } |
| 174 | + |
| 175 | + # Set headers for JSON content and bearer authentication |
| 176 | + headers = { |
| 177 | + "Content-Type": "application/json", |
| 178 | + "Authorization": f"Bearer {api_keys.primary_key}", |
| 179 | + } |
| 180 | + |
| 181 | + response = requests.post(scoring_uri, json=payload, headers=headers) |
| 182 | + |
| 183 | + if response.status_code == 200: |
| 184 | + result = response.json() |
| 185 | + # Extract the model response |
| 186 | + if "choices" in result and len(result["choices"]) > 0: |
| 187 | + answer = result["choices"][0]["message"]["content"] |
| 188 | + print(f"Response received") |
| 189 | + print(f"\n{'='*60}") |
| 190 | + print(answer) |
| 191 | + print(f"{'='*60}\n") |
| 192 | + return result |
| 193 | + else: |
| 194 | + print(f" ✗ Error: {response.status_code}") |
| 195 | + print(f" {response.text}") |
| 196 | + return None |
0 commit comments