Azure AI ML Client Library
The Microsoft Azure Machine Learning Client Library for Python (also known as the 'v2 SDK') is the primary Python interface for interacting with Azure Machine Learning. It enables developers to build, train, and deploy machine learning models, manage workspaces, compute resources, data, environments, and jobs programmatically. It's actively developed, with frequent releases, often on a monthly cadence, aligning with Azure service updates. The current version is 1.32.0.
Warnings
- breaking Migration from Azure ML SDK v1 (`azureml-sdk`) to v2 (`azure-ai-ml`) involves significant breaking changes. The API surface is largely different, with new classes and methods for defining resources and submitting jobs. Projects built on v1 are not directly compatible with v2.
- gotcha Authentication issues are common. `DefaultAzureCredential` attempts multiple authentication flows (e.g., Azure CLI, Managed Identity, Environment Variables, VS Code). If it fails, ensure you are logged in via `az login` or have relevant environment variables (e.g., `AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_SECRET`) correctly set.
- gotcha YAML schema for defining Azure ML resources (jobs, components, environments) can be strict and evolve. Subtle errors in YAML structure or parameter names can lead to validation failures or unexpected behavior.
Install
-
pip install azure-ai-ml -
pip install azure-ai-ml azure-identity
Imports
- MLClient
from azure.ai.ml import MLClient
- DefaultAzureCredential
from azure.identity import DefaultAzureCredential
- CommandJob
from azure.ai.ml.entities import CommandJob
- Environment
from azure.ai.ml.entities import Environment
Quickstart
import os
from azure.ai.ml import MLClient
from azure.identity import DefaultAzureCredential
# Configure Azure credentials and workspace details
subscription_id = os.environ.get('AZURE_SUBSCRIPTION_ID', 'YOUR_SUBSCRIPTION_ID')
resource_group = os.environ.get('AZURE_RESOURCE_GROUP', 'YOUR_RESOURCE_GROUP')
workspace_name = os.environ.get('AZURE_ML_WORKSPACE_NAME', 'YOUR_WORKSPACE_NAME')
# Instantiate DefaultAzureCredential
try:
credential = DefaultAzureCredential()
# Check if credential works by getting a token (optional, but good for early validation)
_ = credential.get_token('https://management.azure.com/.default')
except Exception as e:
print(f"Authentication failed: {e}")
print("Please ensure you are logged in to Azure CLI, VS Code, or have appropriate environment variables set.")
exit(1)
# Create an MLClient instance
ml_client = MLClient(
credential=credential,
subscription_id=subscription_id,
resource_group_name=resource_group,
workspace_name=workspace_name
)
print(f"Connected to Azure ML workspace: {ml_client.workspace_name}")
# Example: List existing environments in the workspace
print("Listing existing environments...")
environments = ml_client.environments.list()
for env in environments:
print(f"- {env.name} (version: {env.version})")