hf-azure 0.3.0__tar.gz

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-0.3.0/LICENSE ADDED
@@ -0,0 +1,25 @@
1
+ Copyright (c) 2026-present Alvaro Bartolome <alvarobartt@gmail.com>
2
+
3
+ Permission is hereby granted, free of charge, to any
4
+ person obtaining a copy of this software and associated
5
+ documentation files (the "Software"), to deal in the
6
+ Software without restriction, including without
7
+ limitation the rights to use, copy, modify, merge,
8
+ publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software
10
+ is furnished to do so, subject to the following
11
+ conditions:
12
+
13
+ The above copyright notice and this permission notice
14
+ shall be included in all copies or substantial portions
15
+ of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19
+ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21
+ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24
+ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25
+ DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,167 @@
1
+ Metadata-Version: 2.4
2
+ Name: hf-azure
3
+ Version: 0.3.0
4
+ Summary: Hugging Face CLI extension to deploy open-models from the Hub, with optimized recipes, on Microsoft Foundry.
5
+ Author: Alvaro Bartolome
6
+ Author-email: Alvaro Bartolome <36760800+alvarobartt@users.noreply.github.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Requires-Dist: azure-identity>=1.25.1
10
+ Requires-Dist: huggingface-hub>=0.26.0
11
+ Requires-Dist: requests>=2.32.0
12
+ Requires-Python: >=3.10
13
+ Project-URL: Homepage, https://github.com/huggingface/hf-azure
14
+ Project-URL: Repository, https://github.com/huggingface/hf-azure
15
+ Project-URL: Issues, https://github.com/huggingface/hf-azure/issues
16
+ Description-Content-Type: text/markdown
17
+
18
+ # `hf-azure`
19
+
20
+ `hf-azure` is an extension for the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/guides/cli) to deploy open models from the Hugging Face Hub on [Microsoft Foundry](https://ai.azure.com/nextgen), with optimized recipes for NVIDIA A100, H100, H200, and AMD MI300X.
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ hf extensions install huggingface/hf-azure
26
+ ```
27
+
28
+ Or install the standalone `hf-azure` command from [PyPI](https://pypi.org/project/hf-azure/) with `uv tool install hf-azure`.
29
+
30
+ ## Authentication
31
+
32
+ Authenticate with `az login`, a service principal, or a managed identity. Set `AZURE_SUBSCRIPTION_ID` and `FOUNDRY_ACCOUNT_NAME` (or pass `--subscription-id` and `--account`) to pick the subscription and Microsoft Foundry resource, or create a resource with:
33
+
34
+ ```bash
35
+ hf azure microsoft-foundry accounts create my-foundry --resource-group my-foundry-rg --location eastus
36
+ ```
37
+
38
+ ## Deploy a model
39
+
40
+ | Model | Size | Default deployment template |
41
+ |---|---|---|
42
+ | [`zai-org/GLM-5.3-Flash`](https://huggingface.co/zai-org/GLM-5.3-Flash) | 321B | 4 x AMD Instinct MI300X at 512K context |
43
+ | [`nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-FP8`](https://huggingface.co/nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-FP8) | 120B (12B active) | 2 x NVIDIA H100 at 256K context |
44
+ | [`google/gemma-4-26B-A4B-it`](https://huggingface.co/google/gemma-4-26B-A4B-it) | 26B (4B active) | 1 x NVIDIA A100 at 256K context |
45
+
46
+ Browse the catalog for each model's GPUs, context lengths, and hourly prices, and check GPU availability with `quota` and `capacity`.
47
+
48
+ ```bash
49
+ hf azure microsoft-foundry models list
50
+ hf azure microsoft-foundry models list --search "gemma 4"
51
+ hf azure microsoft-foundry models google/gemma-4-26B-A4B-it deployment-templates
52
+ hf azure microsoft-foundry deploy google/gemma-4-26B-A4B-it --name my-gemma-4
53
+ ```
54
+
55
+ Deploying uses the default recipe and waits until it's ready, usually around 20 minutes. Pass `--deployment-template 256k-nvidia-h100` for another recipe or `--no-wait` to return immediately, and delete the deployment with `hf azure microsoft-foundry deployments delete my-gemma-4 --wait` to stop billing.
56
+
57
+ ## Use the endpoint
58
+
59
+ Export the key and base URL, then use the deployment name as the model in `/chat/completions` (or `/responses`, where supported).
60
+
61
+ ```bash
62
+ export OPENAI_BASE_URL=$(hf azure microsoft-foundry accounts info -o json | jq -r .openai_base_url)
63
+ export OPENAI_API_KEY=$(hf azure microsoft-foundry accounts keys -o json | jq -r .key1)
64
+ ```
65
+
66
+ ```python
67
+ from openai import OpenAI
68
+
69
+ client = OpenAI()
70
+ completion = client.chat.completions.create(
71
+ model="my-gemma-4",
72
+ messages=[{"role": "user", "content": "What's the capital of France?"}],
73
+ max_completion_tokens=1024,
74
+ )
75
+ print(completion.choices[0].message.content)
76
+ ```
77
+
78
+ Send images as base64 data URIs, as deployments can't fetch remote URLs.
79
+
80
+ ## Coding agents
81
+
82
+ Launch [Pi](https://docs.pi.dev/latest/quickstart) 1.x or [OpenCode](https://opencode.ai/download) 2.x against a ready deployment of a model with tool calling. The launchers configure the endpoint and key, and the deployment name can be omitted when `FOUNDRY_DEPLOYMENT` is set or only one deployment is ready.
83
+
84
+ ```bash
85
+ hf azure microsoft-foundry pi my-gemma-4
86
+ hf azure microsoft-foundry opencode my-gemma-4
87
+ ```
88
+
89
+ Pass harness arguments after `--`, e.g. `--continue` to resume the latest session.
90
+
91
+ ```bash
92
+ hf azure microsoft-foundry pi my-gemma-4 -- -p "Remember the codename Cedar."
93
+ hf azure microsoft-foundry pi my-gemma-4 -- --continue -p "What was the codename?"
94
+ hf azure microsoft-foundry opencode my-gemma-4 -- run "Remember the codename Cedar."
95
+ hf azure microsoft-foundry opencode my-gemma-4 -- run --continue "What was the codename?"
96
+ ```
97
+
98
+ <details>
99
+ <summary>Manual provider setup</summary>
100
+
101
+ The examples use the [endpoint and key](#use-the-endpoint) with the 256K Gemma 4 template and a 4,096 token output limit, so adjust the context limit to match your deployment template.
102
+
103
+ For OpenCode, merge this provider into your project's `opencode.json` and select `foundry/my-gemma-4`.
104
+
105
+ ```json
106
+ {
107
+ "providers": {
108
+ "foundry": {
109
+ "package": "@opencode/ai/providers/openai-compatible",
110
+ "env": ["OPENAI_API_KEY"],
111
+ "settings": {"baseURL": "{env:OPENAI_BASE_URL}"},
112
+ "models": {
113
+ "my-gemma-4": {
114
+ "name": "Gemma 4 26B A4B",
115
+ "capabilities": {"tools": true, "input": ["text"], "output": ["text"]},
116
+ "limit": {"context": 262144, "output": 4096}
117
+ }
118
+ }
119
+ }
120
+ }
121
+ }
122
+ ```
123
+
124
+ For Pi, merge this provider into `~/.pi/agent/models.json`, set `baseUrl` to the value of `OPENAI_BASE_URL`, and select `foundry/my-gemma-4`.
125
+
126
+ ```json
127
+ {
128
+ "providers": {
129
+ "foundry": {
130
+ "baseUrl": "https://my-foundry.services.ai.azure.com/openai/v1",
131
+ "api": "openai-completions",
132
+ "apiKey": "$OPENAI_API_KEY",
133
+ "compat": {"maxTokensField": "max_completion_tokens"},
134
+ "models": [
135
+ {"id": "my-gemma-4", "name": "Gemma 4 26B A4B", "input": ["text"], "contextWindow": 262144, "maxTokens": 4096}
136
+ ]
137
+ }
138
+ }
139
+ }
140
+ ```
141
+
142
+ </details>
143
+
144
+ ## Agent skill
145
+
146
+ Give your agent the [`hf-azure` skill](https://github.com/huggingface/hf-azure/blob/main/skills/hf-azure/SKILL.md) to find models, choose recipes, and manage deployments.
147
+
148
+ ```bash
149
+ npx skills add huggingface/hf-azure --skill hf-azure
150
+ ```
151
+
152
+ ## Commands
153
+
154
+ | `hf azure microsoft-foundry ...` | Description |
155
+ |---|---|
156
+ | `models [list\|<model> [info\|deployment-templates]]` | Browse models and their deployment templates |
157
+ | `deploy <model>` | Deploy a model |
158
+ | `deployments {list,status,wait,scale,delete}` | Manage deployments |
159
+ | `accounts {list,info,keys,create}` | Manage Microsoft Foundry resources |
160
+ | `capacity` / `quota` | Show GPU availability and quota |
161
+ | `pi` / `opencode` | Launch a coding agent on a deployment |
162
+
163
+ Pass `-o json` for machine-readable output. The `microsoft-foundry` prefix is optional for now, e.g. `hf azure deploy`.
164
+
165
+ ## Telemetry
166
+
167
+ The CLI sends anonymous usage events to the Hugging Face Hub with public catalog metadata only (models, deployment templates, accelerators, instances, region, and outcomes), never names, keys, or prompts. Disable it with `HF_HUB_DISABLE_TELEMETRY=1` or `DO_NOT_TRACK=1`.
@@ -0,0 +1,150 @@
1
+ # `hf-azure`
2
+
3
+ `hf-azure` is an extension for the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/guides/cli) to deploy open models from the Hugging Face Hub on [Microsoft Foundry](https://ai.azure.com/nextgen), with optimized recipes for NVIDIA A100, H100, H200, and AMD MI300X.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ hf extensions install huggingface/hf-azure
9
+ ```
10
+
11
+ Or install the standalone `hf-azure` command from [PyPI](https://pypi.org/project/hf-azure/) with `uv tool install hf-azure`.
12
+
13
+ ## Authentication
14
+
15
+ Authenticate with `az login`, a service principal, or a managed identity. Set `AZURE_SUBSCRIPTION_ID` and `FOUNDRY_ACCOUNT_NAME` (or pass `--subscription-id` and `--account`) to pick the subscription and Microsoft Foundry resource, or create a resource with:
16
+
17
+ ```bash
18
+ hf azure microsoft-foundry accounts create my-foundry --resource-group my-foundry-rg --location eastus
19
+ ```
20
+
21
+ ## Deploy a model
22
+
23
+ | Model | Size | Default deployment template |
24
+ |---|---|---|
25
+ | [`zai-org/GLM-5.3-Flash`](https://huggingface.co/zai-org/GLM-5.3-Flash) | 321B | 4 x AMD Instinct MI300X at 512K context |
26
+ | [`nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-FP8`](https://huggingface.co/nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-FP8) | 120B (12B active) | 2 x NVIDIA H100 at 256K context |
27
+ | [`google/gemma-4-26B-A4B-it`](https://huggingface.co/google/gemma-4-26B-A4B-it) | 26B (4B active) | 1 x NVIDIA A100 at 256K context |
28
+
29
+ Browse the catalog for each model's GPUs, context lengths, and hourly prices, and check GPU availability with `quota` and `capacity`.
30
+
31
+ ```bash
32
+ hf azure microsoft-foundry models list
33
+ hf azure microsoft-foundry models list --search "gemma 4"
34
+ hf azure microsoft-foundry models google/gemma-4-26B-A4B-it deployment-templates
35
+ hf azure microsoft-foundry deploy google/gemma-4-26B-A4B-it --name my-gemma-4
36
+ ```
37
+
38
+ Deploying uses the default recipe and waits until it's ready, usually around 20 minutes. Pass `--deployment-template 256k-nvidia-h100` for another recipe or `--no-wait` to return immediately, and delete the deployment with `hf azure microsoft-foundry deployments delete my-gemma-4 --wait` to stop billing.
39
+
40
+ ## Use the endpoint
41
+
42
+ Export the key and base URL, then use the deployment name as the model in `/chat/completions` (or `/responses`, where supported).
43
+
44
+ ```bash
45
+ export OPENAI_BASE_URL=$(hf azure microsoft-foundry accounts info -o json | jq -r .openai_base_url)
46
+ export OPENAI_API_KEY=$(hf azure microsoft-foundry accounts keys -o json | jq -r .key1)
47
+ ```
48
+
49
+ ```python
50
+ from openai import OpenAI
51
+
52
+ client = OpenAI()
53
+ completion = client.chat.completions.create(
54
+ model="my-gemma-4",
55
+ messages=[{"role": "user", "content": "What's the capital of France?"}],
56
+ max_completion_tokens=1024,
57
+ )
58
+ print(completion.choices[0].message.content)
59
+ ```
60
+
61
+ Send images as base64 data URIs, as deployments can't fetch remote URLs.
62
+
63
+ ## Coding agents
64
+
65
+ Launch [Pi](https://docs.pi.dev/latest/quickstart) 1.x or [OpenCode](https://opencode.ai/download) 2.x against a ready deployment of a model with tool calling. The launchers configure the endpoint and key, and the deployment name can be omitted when `FOUNDRY_DEPLOYMENT` is set or only one deployment is ready.
66
+
67
+ ```bash
68
+ hf azure microsoft-foundry pi my-gemma-4
69
+ hf azure microsoft-foundry opencode my-gemma-4
70
+ ```
71
+
72
+ Pass harness arguments after `--`, e.g. `--continue` to resume the latest session.
73
+
74
+ ```bash
75
+ hf azure microsoft-foundry pi my-gemma-4 -- -p "Remember the codename Cedar."
76
+ hf azure microsoft-foundry pi my-gemma-4 -- --continue -p "What was the codename?"
77
+ hf azure microsoft-foundry opencode my-gemma-4 -- run "Remember the codename Cedar."
78
+ hf azure microsoft-foundry opencode my-gemma-4 -- run --continue "What was the codename?"
79
+ ```
80
+
81
+ <details>
82
+ <summary>Manual provider setup</summary>
83
+
84
+ The examples use the [endpoint and key](#use-the-endpoint) with the 256K Gemma 4 template and a 4,096 token output limit, so adjust the context limit to match your deployment template.
85
+
86
+ For OpenCode, merge this provider into your project's `opencode.json` and select `foundry/my-gemma-4`.
87
+
88
+ ```json
89
+ {
90
+ "providers": {
91
+ "foundry": {
92
+ "package": "@opencode/ai/providers/openai-compatible",
93
+ "env": ["OPENAI_API_KEY"],
94
+ "settings": {"baseURL": "{env:OPENAI_BASE_URL}"},
95
+ "models": {
96
+ "my-gemma-4": {
97
+ "name": "Gemma 4 26B A4B",
98
+ "capabilities": {"tools": true, "input": ["text"], "output": ["text"]},
99
+ "limit": {"context": 262144, "output": 4096}
100
+ }
101
+ }
102
+ }
103
+ }
104
+ }
105
+ ```
106
+
107
+ For Pi, merge this provider into `~/.pi/agent/models.json`, set `baseUrl` to the value of `OPENAI_BASE_URL`, and select `foundry/my-gemma-4`.
108
+
109
+ ```json
110
+ {
111
+ "providers": {
112
+ "foundry": {
113
+ "baseUrl": "https://my-foundry.services.ai.azure.com/openai/v1",
114
+ "api": "openai-completions",
115
+ "apiKey": "$OPENAI_API_KEY",
116
+ "compat": {"maxTokensField": "max_completion_tokens"},
117
+ "models": [
118
+ {"id": "my-gemma-4", "name": "Gemma 4 26B A4B", "input": ["text"], "contextWindow": 262144, "maxTokens": 4096}
119
+ ]
120
+ }
121
+ }
122
+ }
123
+ ```
124
+
125
+ </details>
126
+
127
+ ## Agent skill
128
+
129
+ Give your agent the [`hf-azure` skill](https://github.com/huggingface/hf-azure/blob/main/skills/hf-azure/SKILL.md) to find models, choose recipes, and manage deployments.
130
+
131
+ ```bash
132
+ npx skills add huggingface/hf-azure --skill hf-azure
133
+ ```
134
+
135
+ ## Commands
136
+
137
+ | `hf azure microsoft-foundry ...` | Description |
138
+ |---|---|
139
+ | `models [list\|<model> [info\|deployment-templates]]` | Browse models and their deployment templates |
140
+ | `deploy <model>` | Deploy a model |
141
+ | `deployments {list,status,wait,scale,delete}` | Manage deployments |
142
+ | `accounts {list,info,keys,create}` | Manage Microsoft Foundry resources |
143
+ | `capacity` / `quota` | Show GPU availability and quota |
144
+ | `pi` / `opencode` | Launch a coding agent on a deployment |
145
+
146
+ Pass `-o json` for machine-readable output. The `microsoft-foundry` prefix is optional for now, e.g. `hf azure deploy`.
147
+
148
+ ## Telemetry
149
+
150
+ The CLI sends anonymous usage events to the Hugging Face Hub with public catalog metadata only (models, deployment templates, accelerators, instances, region, and outcomes), never names, keys, or prompts. Disable it with `HF_HUB_DISABLE_TELEMETRY=1` or `DO_NOT_TRACK=1`.
@@ -0,0 +1,54 @@
1
+ [project]
2
+ name = "hf-azure"
3
+ version = "0.3.0"
4
+ description = "Hugging Face CLI extension to deploy open-models from the Hub, with optimized recipes, on Microsoft Foundry."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.10"
9
+ dependencies = [
10
+ "azure-identity>=1.25.1",
11
+ "huggingface-hub>=0.26.0",
12
+ "requests>=2.32.0",
13
+ ]
14
+
15
+ [[project.authors]]
16
+ name = "Alvaro Bartolome"
17
+ email = "36760800+alvarobartt@users.noreply.github.com"
18
+
19
+ [project.urls]
20
+ Homepage = "https://github.com/huggingface/hf-azure"
21
+ Repository = "https://github.com/huggingface/hf-azure"
22
+ Issues = "https://github.com/huggingface/hf-azure/issues"
23
+
24
+ [project.scripts]
25
+ hf-azure = "hf_azure.cli:main"
26
+
27
+ [[tool.uv.index]]
28
+ url = "https://pypi.org/simple"
29
+ default = true
30
+
31
+ [tool.ruff]
32
+ line-length = 119
33
+
34
+ [tool.ruff.lint]
35
+ select = [
36
+ "E",
37
+ "F",
38
+ "I",
39
+ "UP",
40
+ "B",
41
+ ]
42
+
43
+ [build-system]
44
+ requires = ["uv_build>=0.9.5,<0.11.0"]
45
+ build-backend = "uv_build"
46
+
47
+ [dependency-groups]
48
+ lint = [
49
+ "pre-commit>=4.5.1",
50
+ "ruff>=0.14.10",
51
+ "ty>=0.0.1a32",
52
+ "types-requests>=2.32.0",
53
+ ]
54
+ test = ["pytest>=8.4.0"]
@@ -0,0 +1,49 @@
1
+ [project]
2
+ name = "hf-azure"
3
+ version = "0.3.0"
4
+ description = "Hugging Face CLI extension to deploy open-models from the Hub, with optimized recipes, on Microsoft Foundry."
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Alvaro Bartolome", email = "36760800+alvarobartt@users.noreply.github.com" }
8
+ ]
9
+ license = "MIT"
10
+ license-files = ["LICENSE"]
11
+ requires-python = ">=3.10"
12
+ dependencies = [
13
+ "azure-identity>=1.25.1",
14
+ "huggingface-hub>=0.26.0",
15
+ "requests>=2.32.0",
16
+ ]
17
+
18
+ [project.urls]
19
+ Homepage = "https://github.com/huggingface/hf-azure"
20
+ Repository = "https://github.com/huggingface/hf-azure"
21
+ Issues = "https://github.com/huggingface/hf-azure/issues"
22
+
23
+ [project.scripts]
24
+ hf-azure = "hf_azure.cli:main"
25
+
26
+ [[tool.uv.index]]
27
+ url = "https://pypi.org/simple"
28
+ default = true
29
+
30
+ [build-system]
31
+ requires = ["uv_build>=0.9.5,<0.11.0"]
32
+ build-backend = "uv_build"
33
+
34
+ [dependency-groups]
35
+ lint = [
36
+ "pre-commit>=4.5.1",
37
+ "ruff>=0.14.10",
38
+ "ty>=0.0.1a32",
39
+ "types-requests>=2.32.0",
40
+ ]
41
+ test = [
42
+ "pytest>=8.4.0",
43
+ ]
44
+
45
+ [tool.ruff]
46
+ line-length = 119
47
+
48
+ [tool.ruff.lint]
49
+ select = ["E", "F", "I", "UP", "B"]
File without changes
@@ -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
+ ]
@@ -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