hf-azure 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
hf_azure/__init__.py ADDED
File without changes
hf_azure/accounts.py ADDED
@@ -0,0 +1,172 @@
1
+ import logging
2
+ import time
3
+ from dataclasses import dataclass
4
+ from typing import Any
5
+
6
+ from hf_azure.azure import ARM, AzureClient
7
+ from hf_azure.errors import FoundryError, NotFoundError
8
+
9
+ logger = logging.getLogger("hf_azure")
10
+
11
+ OFFER = "GlobalManagedCompute"
12
+ API_VERSION = "2026-11-01"
13
+ PROVIDER = "providers/Microsoft.CognitiveServices"
14
+
15
+
16
+ @dataclass
17
+ class Account:
18
+ subscription_id: str
19
+ resource_group: str
20
+ name: str
21
+ location: str
22
+
23
+ @property
24
+ def endpoint(self) -> str:
25
+ return f"https://{self.name}.services.ai.azure.com"
26
+
27
+ @property
28
+ def openai_base_url(self) -> str:
29
+ return f"{self.endpoint}/openai/v1"
30
+
31
+ @property
32
+ def resource_url(self) -> str:
33
+ return (
34
+ f"{ARM}/subscriptions/{self.subscription_id}/resourceGroups/{self.resource_group}/{PROVIDER}"
35
+ f"/accounts/{self.name}"
36
+ )
37
+
38
+
39
+ def resource_group(resource_id: str) -> str:
40
+ return resource_id.split("/resourceGroups/", 1)[1].split("/", 1)[0]
41
+
42
+
43
+ class Accounts:
44
+ def __init__(self, azure: AzureClient, subscription_id: str) -> None:
45
+ self.azure = azure
46
+ self.subscription_id = subscription_id
47
+ self.params = {"api-version": API_VERSION}
48
+
49
+ @property
50
+ def subscription_url(self) -> str:
51
+ return f"{ARM}/subscriptions/{self.subscription_id}"
52
+
53
+ def all(self) -> list[Account]:
54
+ items = self.azure.paginate(
55
+ f"{self.subscription_url}/{PROVIDER}/accounts",
56
+ self.params,
57
+ not_found=f"Subscription {self.subscription_id} not found",
58
+ )
59
+ return [
60
+ Account(self.subscription_id, resource_group(item["id"]), item["name"], item["location"])
61
+ for item in items
62
+ if item.get("kind") == "AIServices"
63
+ ]
64
+
65
+ def get(self, name: str | None = None) -> Account:
66
+ accounts = self.all()
67
+ if name:
68
+ for account in accounts:
69
+ if account.name == name:
70
+ return account
71
+ raise NotFoundError(
72
+ f"Microsoft Foundry resource '{name}' not found in subscription {self.subscription_id}"
73
+ )
74
+ if len(accounts) == 1:
75
+ return accounts[0]
76
+ if not accounts:
77
+ raise NotFoundError(
78
+ f"No Microsoft Foundry resources found in subscription {self.subscription_id}, "
79
+ "create one with `hf azure microsoft-foundry accounts create`"
80
+ )
81
+ names = ", ".join(account.name for account in accounts)
82
+ raise ValueError(f"Found {len(accounts)} Microsoft Foundry resources, set --account to one of: {names}")
83
+
84
+ def provision(self, url: str, body: dict[str, Any], interval: int = 10) -> None:
85
+ self.azure.request("PUT", url, params=self.params, json=body)
86
+ while True:
87
+ state = self.azure.request("GET", url, params=self.params).get("properties", {}).get("provisioningState")
88
+ if state == "Succeeded":
89
+ return
90
+ if state in {"Failed", "Canceled"}:
91
+ raise FoundryError(f"{url.split('/providers/', 1)[-1]} ended in state {state}")
92
+ time.sleep(interval)
93
+
94
+ def create(
95
+ self, name: str, resource_group: str, location: str, project: str | None = None, interval: int = 10
96
+ ) -> Account:
97
+ logger.info("Creating resource group '%s' in %s", resource_group, location)
98
+ self.azure.request(
99
+ "PUT",
100
+ f"{self.subscription_url}/resourcegroups/{resource_group}",
101
+ params={"api-version": "2021-04-01"},
102
+ json={"location": location},
103
+ )
104
+ account = Account(self.subscription_id, resource_group, name, location)
105
+ logger.info("Creating Microsoft Foundry resource '%s'", name)
106
+ self.provision(
107
+ account.resource_url,
108
+ {
109
+ "location": location,
110
+ "kind": "AIServices",
111
+ "sku": {"name": "S0"},
112
+ "identity": {"type": "SystemAssigned"},
113
+ "properties": {
114
+ "customSubDomainName": name,
115
+ "allowProjectManagement": True,
116
+ "publicNetworkAccess": "Enabled",
117
+ },
118
+ },
119
+ interval,
120
+ )
121
+ project = project or f"{name}-project"
122
+ logger.info("Creating Microsoft Foundry project '%s'", project)
123
+ self.provision(
124
+ f"{account.resource_url}/projects/{project}",
125
+ {"location": location, "identity": {"type": "SystemAssigned"}, "properties": {}},
126
+ interval,
127
+ )
128
+ return account
129
+
130
+ def keys(self, account: Account) -> dict[str, str]:
131
+ keys = self.azure.request(
132
+ "POST",
133
+ f"{account.resource_url}/listKeys",
134
+ not_found=f"Microsoft Foundry resource '{account.name}' not found",
135
+ params=self.params,
136
+ )
137
+ return {"key1": keys.get("key1", ""), "key2": keys.get("key2", "")}
138
+
139
+ def capacity(self) -> list[dict[str, Any]]:
140
+ items = self.azure.paginate(
141
+ f"{self.subscription_url}/{PROVIDER}/managedComputeCapacities",
142
+ {**self.params, "offer": OFFER},
143
+ not_found=f"Subscription {self.subscription_id} not found",
144
+ )
145
+ return [
146
+ {
147
+ "accelerator_type": item["properties"]["acceleratorType"],
148
+ "available": item["properties"]["availableAccelerators"],
149
+ "largest_deployment": {
150
+ size["modelInstanceAcceleratorCount"]: size["largestDeploymentCapacity"]
151
+ for size in item["properties"].get("deploymentSizeCapacities", [])
152
+ },
153
+ }
154
+ for item in items
155
+ if item["properties"].get("offerScope") == "Global"
156
+ ]
157
+
158
+ def quota(self, location: str) -> list[dict[str, Any]]:
159
+ items = self.azure.paginate(
160
+ f"{self.subscription_url}/{PROVIDER}/locations/{location}/managedComputeUsages",
161
+ self.params,
162
+ not_found=f"Location '{location}' not found",
163
+ )
164
+ return [
165
+ {
166
+ "accelerator_type": item["name"]["value"].rsplit(".", 1)[-1],
167
+ "used": item["currentValue"],
168
+ "limit": item["limit"],
169
+ }
170
+ for item in items
171
+ if item.get("offerScope") == "Global"
172
+ ]
hf_azure/azure.py ADDED
@@ -0,0 +1,62 @@
1
+ from typing import Any
2
+
3
+ import requests
4
+ from azure.core.credentials import TokenCredential
5
+ from azure.identity import DefaultAzureCredential
6
+ from requests.adapters import HTTPAdapter
7
+ from urllib3.util.retry import Retry
8
+
9
+ from hf_azure.errors import AzureRequestError, NotFoundError
10
+
11
+ ARM = "https://management.azure.com"
12
+ RETRY = Retry(total=5, backoff_factor=2, status_forcelist=[429, 500, 502, 503, 504], respect_retry_after_header=True)
13
+
14
+
15
+ def session_with_retries() -> requests.Session:
16
+ session = requests.Session()
17
+ session.mount("https://", HTTPAdapter(max_retries=RETRY))
18
+ return session
19
+
20
+
21
+ class AzureClient:
22
+ def __init__(self, credential: TokenCredential | None = None, session: requests.Session | None = None) -> None:
23
+ self.credential = credential or DefaultAzureCredential(exclude_interactive_browser_credential=True)
24
+ self.session = session or session_with_retries()
25
+
26
+ def request(self, method: str, url: str, not_found: str | None = None, **kwargs: Any) -> Any:
27
+ token = self.credential.get_token(f"{ARM}/.default").token
28
+ headers = {"Authorization": f"Bearer {token}"}
29
+ try:
30
+ response = self.session.request(method, url, headers=headers, timeout=120, **kwargs)
31
+ except requests.RequestException as error:
32
+ raise AzureRequestError(503, f"{method} {url.split('?')[0]} failed: {error}") from error
33
+ if response.status_code == 404:
34
+ raise NotFoundError(not_found or f"{url.split('?')[0]} does not exist")
35
+ if not response.ok:
36
+ raise AzureRequestError(response.status_code, error_message(response), error_code(response))
37
+ return response.json() if response.content else {}
38
+
39
+ def paginate(self, url: str, params: dict[str, str] | None = None, not_found: str | None = None) -> list[Any]:
40
+ items: list[Any] = []
41
+ next_url: str | None = url
42
+ while next_url:
43
+ data = self.request("GET", next_url, not_found=not_found, params=params)
44
+ items.extend(data.get("value", []))
45
+ next_url, params = data.get("nextLink"), None
46
+ return items
47
+
48
+
49
+ def error_code(response: requests.Response) -> str | None:
50
+ try:
51
+ code = response.json()["error"]["code"]
52
+ except (ValueError, KeyError, TypeError):
53
+ return None
54
+ return code if isinstance(code, str) else None
55
+
56
+
57
+ def error_message(response: requests.Response) -> str:
58
+ try:
59
+ error = response.json().get("error", {})
60
+ return f"{error['code']}: {error['message']}"
61
+ except (ValueError, KeyError, TypeError, AttributeError):
62
+ return response.text or response.reason
hf_azure/cli.py ADDED
@@ -0,0 +1,298 @@
1
+ import argparse
2
+ import json
3
+ import logging
4
+ import sys
5
+ import time
6
+ from dataclasses import asdict, is_dataclass
7
+ from typing import Any
8
+
9
+ from azure.core.exceptions import ClientAuthenticationError
10
+
11
+ from hf_azure import telemetry
12
+ from hf_azure.client import Foundry
13
+ from hf_azure.deployments import Deployment
14
+ from hf_azure.errors import FoundryError
15
+ from hf_azure.harnesses import HARNESSES, launch
16
+
17
+ logger = logging.getLogger("hf_azure")
18
+
19
+ TEMPLATE_COLUMNS = [
20
+ "name",
21
+ "accelerator_type",
22
+ "accelerator_count",
23
+ "max_model_len",
24
+ "environment",
25
+ "price_per_hour",
26
+ "default",
27
+ ]
28
+ # Microsoft Foundry is the only platform for now, so its commands also work without the prefix.
29
+ PLATFORM = "microsoft-foundry"
30
+ DEPLOYMENT_COLUMNS = ["name", "state", "model", "template", "accelerator_type", "instances"]
31
+ EXPORTED_PROPERTIES = ("uri", "url", "endpoint", "openai_base_url")
32
+
33
+
34
+ def serialize(data: Any) -> Any:
35
+ if isinstance(data, list):
36
+ return [serialize(item) for item in data]
37
+ if is_dataclass(data) and not isinstance(data, type):
38
+ values = asdict(data)
39
+ for prop in EXPORTED_PROPERTIES:
40
+ if isinstance(getattr(type(data), prop, None), property):
41
+ values[prop] = getattr(data, prop)
42
+ return values
43
+ return data
44
+
45
+
46
+ def table(rows: list[dict[str, Any]], columns: list[str]) -> str:
47
+ cells = [["" if row.get(c) is None else str(row.get(c)) for c in columns] for row in rows]
48
+ widths = [max(len(c), *(len(r[i]) for r in cells)) for i, c in enumerate(columns)]
49
+ lines = [[c.upper() for c in columns], *cells]
50
+ return "\n".join(" ".join(v.ljust(w) for v, w in zip(line, widths, strict=True)).rstrip() for line in lines)
51
+
52
+
53
+ def render(data: Any, columns: list[str] | None) -> str:
54
+ if isinstance(data, dict):
55
+ width = max(len(k) for k in data)
56
+ return "\n".join(
57
+ f"{k.ljust(width)} {', '.join(map(str, v)) if isinstance(v, list) else ('' if v is None else v)}"
58
+ for k, v in data.items()
59
+ )
60
+ if columns:
61
+ return table(data, columns)
62
+ return "\n".join(map(str, data))
63
+
64
+
65
+ def emit(args: argparse.Namespace, data: Any, columns: list[str] | None = None, empty: str = "") -> None:
66
+ data = serialize(data)
67
+ if args.output == "json":
68
+ sys.stdout.write(json.dumps(data, indent=2) + "\n")
69
+ elif not data:
70
+ logger.warning(empty)
71
+ else:
72
+ sys.stdout.write(render(data, columns) + "\n")
73
+
74
+
75
+ def error_fields(error: Exception) -> telemetry.Fields:
76
+ # Only the error class and Azure's error code, e.g. InsufficientQuota, never the message.
77
+ return {"status": "error", "error": type(error).__name__, "error_code": getattr(error, "code", None)}
78
+
79
+
80
+ def wait(foundry: Foundry, name: str, fields: telemetry.Fields) -> Deployment:
81
+ start = time.monotonic()
82
+ try:
83
+ deployment = foundry.deployments.wait(name)
84
+ except FoundryError as error:
85
+ telemetry.send("failed", {**fields, **error_fields(error), "wait_s": int(time.monotonic() - start)})
86
+ raise
87
+ telemetry.send("ready", {**fields, "wait_s": int(time.monotonic() - start)})
88
+ return deployment
89
+
90
+
91
+ def run(args: argparse.Namespace) -> int | None:
92
+ foundry = Foundry(subscription_id=args.subscription_id, account_name=args.account)
93
+ action = getattr(args, "action", None)
94
+ model_id = getattr(args, "model_id", None)
95
+ if args.command == "models":
96
+ if model_id == "list" and action is None:
97
+ model_id = None
98
+ if model_id is not None:
99
+ if args.search:
100
+ raise ValueError("Use either a model ID or --search, not both")
101
+ action = action or "info"
102
+ match args.command, action:
103
+ case "models", None if model_id is None:
104
+ scope = f"match '{args.search}'" if args.search else "are available"
105
+ empty = f"No models {scope} in the Hugging Face collection on Microsoft Foundry"
106
+ emit(args, foundry.registry.models(args.search), empty=empty)
107
+ case "models", "info":
108
+ model = foundry.registry.model(args.model_id, args.version)
109
+ telemetry.send("view", {**telemetry.model_fields(model), "action": "info"})
110
+ emit(args, model)
111
+ case "models", "deployment-templates":
112
+ model = foundry.registry.model(args.model_id, args.version)
113
+ telemetry.send("view", {**telemetry.model_fields(model), "action": "deployment-templates"})
114
+ empty = f"{args.model_id} has no deployment templates"
115
+ emit(args, foundry.registry.templates(model, foundry.prices), TEMPLATE_COLUMNS, empty)
116
+ case "deploy", _:
117
+ model, template = foundry.plan(args.model_id, args.deployment_template, args.instances, args.version)
118
+ fields = {
119
+ **telemetry.model_fields(model),
120
+ **telemetry.template_fields(model, template),
121
+ "instances": args.instances,
122
+ "wait": not args.no_wait,
123
+ }
124
+ try:
125
+ fields["region"] = foundry.account.location
126
+ deployment = foundry.deployments.create(model, template, args.name, args.instances)
127
+ except (FoundryError, ValueError) as error:
128
+ telemetry.send("deploy", {**fields, **error_fields(error)})
129
+ raise
130
+ telemetry.send("deploy", {**fields, "status": "created"})
131
+ emit(args, deployment if args.no_wait else wait(foundry, deployment.name, fields))
132
+ case "deployments", "list":
133
+ empty = f"No deployments in the Microsoft Foundry resource '{foundry.account.name}'"
134
+ emit(args, foundry.deployments.all(), DEPLOYMENT_COLUMNS, empty)
135
+ case "deployments", "status":
136
+ emit(args, foundry.deployments.get(args.name))
137
+ case "deployments", "wait":
138
+ fields = {
139
+ **telemetry.deployment_fields(foundry.deployments.get(args.name)),
140
+ "region": foundry.account.location,
141
+ }
142
+ emit(args, wait(foundry, args.name, fields))
143
+ case "deployments", "scale":
144
+ deployment = foundry.deployments.update(args.name, args.instances)
145
+ fields = {**telemetry.deployment_fields(deployment), "region": foundry.account.location}
146
+ telemetry.send("scale", fields)
147
+ emit(args, deployment if args.no_wait else wait(foundry, deployment.name, fields))
148
+ case "deployments", "delete":
149
+ deployment = foundry.deployments.delete(args.name)
150
+ telemetry.send("delete", {**telemetry.deployment_fields(deployment), "region": foundry.account.location})
151
+ if args.wait:
152
+ foundry.deployments.wait_deleted(args.name)
153
+ case "accounts", "list":
154
+ empty = f"No Microsoft Foundry resources found in subscription {foundry.subscription_id}"
155
+ emit(args, foundry.accounts.all(), ["name", "resource_group", "location", "endpoint"], empty)
156
+ case "accounts", "info":
157
+ emit(args, foundry.account)
158
+ case "accounts", "create":
159
+ account = foundry.accounts.create(args.name, args.resource_group, args.location, args.project)
160
+ telemetry.send("account", {"region": account.location})
161
+ emit(args, account)
162
+ case "accounts", "keys":
163
+ emit(args, foundry.accounts.keys(foundry.account))
164
+ case "capacity", _:
165
+ empty = f"No managed compute capacity available in subscription {foundry.subscription_id}"
166
+ emit(args, foundry.accounts.capacity(), ["accelerator_type", "available", "largest_deployment"], empty)
167
+ case "quota", _:
168
+ location = args.location or foundry.account.location
169
+ empty = f"No managed compute quota in {location} for subscription {foundry.subscription_id}"
170
+ emit(args, foundry.accounts.quota(location), ["accelerator_type", "used", "limit"], empty)
171
+ case "pi" | "opencode", _:
172
+ return launch(foundry, args.command, args.deployment, args.harness_args)
173
+ return None
174
+
175
+
176
+ def parser() -> argparse.ArgumentParser:
177
+ common = argparse.ArgumentParser(add_help=False)
178
+ common.add_argument("--subscription-id", help="Azure subscription ID, defaults to AZURE_SUBSCRIPTION_ID")
179
+ common.add_argument("--account", help="Microsoft Foundry resource name, defaults to FOUNDRY_ACCOUNT_NAME")
180
+ common.add_argument(
181
+ "-o", "--output", choices=["table", "json"], default="table", help="Output format, json also applies to errors"
182
+ )
183
+
184
+ root = argparse.ArgumentParser(
185
+ prog="hf azure microsoft-foundry",
186
+ description="Deploy open models from the Hugging Face collection on Microsoft Foundry",
187
+ epilog=f"The {PLATFORM} prefix is optional for now, e.g. `hf azure deploy` is `hf azure {PLATFORM} deploy`.",
188
+ )
189
+ commands = root.add_subparsers(dest="command", required=True)
190
+
191
+ def group(name: str, help: str) -> argparse._SubParsersAction:
192
+ return commands.add_parser(name, help=help).add_subparsers(dest="action", required=True)
193
+
194
+ models = commands.add_parser(
195
+ "models",
196
+ parents=[common],
197
+ help="Browse the Hugging Face collection on Microsoft Foundry",
198
+ description="Run `hf azure microsoft-foundry models list` to list models, or see a model’s deployment "
199
+ "templates with `hf azure microsoft-foundry models google/gemma-4-31B-it deployment-templates`",
200
+ )
201
+ models.add_argument(
202
+ "model_id", nargs="?", help="Pass list or omit this argument to browse, or enter a Hub ID to show a model"
203
+ )
204
+ models.add_argument("action", nargs="?", choices=["info", "deployment-templates"], help="Defaults to info")
205
+ models.add_argument("--search", help="Filter the models by name, e.g. 'gemma 4'")
206
+ models.add_argument("--version", help="Model version, defaults to the latest")
207
+
208
+ deploy = commands.add_parser("deploy", parents=[common], help="Deploy a model")
209
+ deploy.add_argument("model_id", help="Hub ID, e.g. google/gemma-4-31B-it")
210
+ deploy.add_argument("--version", help="Model version, defaults to the latest")
211
+ deploy.add_argument(
212
+ "--deployment-template",
213
+ "--template",
214
+ dest="deployment_template",
215
+ help="Deployment template name (or its suffix, e.g. 256k-nvidia-h100), defaults to the model's default",
216
+ )
217
+ deploy.add_argument(
218
+ "--name",
219
+ help="Deployment name, i.e. the model to set in requests, defaults to <author>--<model>--<7-digit timestamp>",
220
+ )
221
+ deploy.add_argument("--instances", type=int, default=1, help="Number of instances")
222
+ deploy.add_argument("--no-wait", action="store_true", help="Return without waiting for the deployment")
223
+
224
+ deployments = group("deployments", "Manage the deployments")
225
+ deployments.add_parser("list", parents=[common], help="List the deployments")
226
+ for action, help in [
227
+ ("status", "Show a deployment"),
228
+ ("wait", "Wait until a deployment succeeds"),
229
+ ("scale", "Change the number of instances"),
230
+ ("delete", "Delete a deployment"),
231
+ ]:
232
+ sub = deployments.add_parser(action, parents=[common], help=help)
233
+ sub.add_argument("name")
234
+ if action == "scale":
235
+ sub.add_argument("--instances", type=int, required=True)
236
+ sub.add_argument("--no-wait", action="store_true")
237
+ if action == "delete":
238
+ sub.add_argument("--wait", action="store_true", help="Wait until the deployment is deleted")
239
+
240
+ accounts = group("accounts", "Manage the Microsoft Foundry resources")
241
+ accounts.add_parser("list", parents=[common], help="List the Microsoft Foundry resources")
242
+ accounts.add_parser("info", parents=[common], help="Show the Microsoft Foundry resource and its endpoint")
243
+ accounts.add_parser("keys", parents=[common], help="Show the API keys of the Microsoft Foundry resource")
244
+ create = accounts.add_parser("create", parents=[common], help="Create a Microsoft Foundry resource")
245
+ create.add_argument("name")
246
+ create.add_argument("--resource-group", required=True, help="Created if it doesn't exist")
247
+ create.add_argument("--location", required=True, help="Azure region, e.g. eastus")
248
+ create.add_argument("--project", help="Project name, defaults to <name>-project")
249
+
250
+ commands.add_parser("capacity", parents=[common], help="Show the available accelerators")
251
+ quota = commands.add_parser("quota", parents=[common], help="Show the managed compute quota")
252
+ quota.add_argument("--location", help="Azure region, defaults to the Microsoft Foundry resource's")
253
+
254
+ for harness in HARNESSES:
255
+ agent = commands.add_parser(
256
+ harness, parents=[common], help=f"Launch {harness} with a Microsoft Foundry deployment"
257
+ )
258
+ agent.add_argument(
259
+ "deployment",
260
+ nargs="?",
261
+ help="Deployment name, defaults to FOUNDRY_DEPLOYMENT or the only ready deployment",
262
+ )
263
+ agent.epilog = f"Put {harness} arguments after --. Output from the harness uses its own format."
264
+
265
+ return root
266
+
267
+
268
+ def main() -> int:
269
+ logging.basicConfig(level=logging.WARNING, format="%(levelname)s %(message)s")
270
+ logger.setLevel(logging.INFO)
271
+ arguments = sys.argv[1:]
272
+ if arguments and arguments[0] == PLATFORM:
273
+ arguments = arguments[1:]
274
+ harness_args: list[str] = []
275
+ if arguments and arguments[0] in HARNESSES and "--" in arguments:
276
+ separator = arguments.index("--")
277
+ arguments, harness_args = arguments[:separator], arguments[separator + 1 :]
278
+ args = parser().parse_args(arguments)
279
+ args.harness_args = harness_args
280
+ try:
281
+ return run(args) or 0
282
+ except (FoundryError, ValueError, FileNotFoundError, ClientAuthenticationError) as error:
283
+ message = error.message if isinstance(error, ClientAuthenticationError) else str(error)
284
+ if isinstance(error, ClientAuthenticationError):
285
+ message = f"Azure authentication failed, run `az login` first: {message}"
286
+ if getattr(args, "output", "table") == "json":
287
+ sys.stderr.write(json.dumps({"error": type(error).__name__, "message": message}) + "\n")
288
+ else:
289
+ logger.error(message)
290
+ return 1
291
+ except KeyboardInterrupt:
292
+ return 130
293
+ finally:
294
+ telemetry.flush()
295
+
296
+
297
+ if __name__ == "__main__":
298
+ raise SystemExit(main())
hf_azure/client.py ADDED
@@ -0,0 +1,80 @@
1
+ import os
2
+ import subprocess
3
+ from functools import cached_property
4
+
5
+ import requests
6
+ from azure.core.credentials import TokenCredential
7
+
8
+ from hf_azure.accounts import Account, Accounts
9
+ from hf_azure.azure import ARM, AzureClient
10
+ from hf_azure.deployments import Deployment, Deployments
11
+ from hf_azure.pricing import Prices
12
+ from hf_azure.registry import Model, Registry, Template
13
+
14
+
15
+ class Foundry:
16
+ def __init__(
17
+ self,
18
+ subscription_id: str | None = None,
19
+ account_name: str | None = None,
20
+ credential: TokenCredential | None = None,
21
+ session: requests.Session | None = None,
22
+ ) -> None:
23
+ self.azure = AzureClient(credential=credential, session=session)
24
+ self.registry = Registry(self.azure)
25
+ self._subscription_id = subscription_id or os.getenv("AZURE_SUBSCRIPTION_ID")
26
+ self._account_name = account_name or os.getenv("FOUNDRY_ACCOUNT_NAME")
27
+
28
+ @cached_property
29
+ def subscription_id(self) -> str:
30
+ if self._subscription_id:
31
+ return self._subscription_id
32
+ try:
33
+ result = subprocess.run(
34
+ ["az", "account", "show", "--query", "id", "-o", "tsv"], capture_output=True, text=True
35
+ )
36
+ if result.returncode == 0 and result.stdout.strip():
37
+ return result.stdout.strip()
38
+ except FileNotFoundError:
39
+ pass
40
+ subscriptions = self.azure.paginate(f"{ARM}/subscriptions", {"api-version": "2022-12-01"})
41
+ if len(subscriptions) != 1:
42
+ raise ValueError(
43
+ f"Found {len(subscriptions)} Azure subscriptions, set --subscription-id or AZURE_SUBSCRIPTION_ID"
44
+ )
45
+ return subscriptions[0]["subscriptionId"]
46
+
47
+ @cached_property
48
+ def accounts(self) -> Accounts:
49
+ return Accounts(self.azure, self.subscription_id)
50
+
51
+ @cached_property
52
+ def account(self) -> Account:
53
+ return self.accounts.get(self._account_name)
54
+
55
+ @cached_property
56
+ def deployments(self) -> Deployments:
57
+ return Deployments(self.azure, self.account)
58
+
59
+ @cached_property
60
+ def prices(self) -> Prices:
61
+ return Prices(self.azure.session)
62
+
63
+ def plan(
64
+ self, model_id: str, template: str | None = None, instances: int = 1, version: str | None = None
65
+ ) -> tuple[Model, Template]:
66
+ model = self.registry.model(model_id, version)
67
+ selected = self.registry.resolve_template(model, template)
68
+ selected.price_per_hour = self.prices.hourly(selected.accelerator_type, selected.accelerator_count, instances)
69
+ return model, selected
70
+
71
+ def deploy(
72
+ self,
73
+ model_id: str,
74
+ template: str | None = None,
75
+ name: str | None = None,
76
+ instances: int = 1,
77
+ version: str | None = None,
78
+ ) -> Deployment:
79
+ model, selected = self.plan(model_id, template, instances, version)
80
+ return self.deployments.create(model, selected, name, instances)