grad-sdk 0.2.0a1__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.
- grad_sdk-0.2.0a1/LICENSE +21 -0
- grad_sdk-0.2.0a1/PKG-INFO +139 -0
- grad_sdk-0.2.0a1/README.md +108 -0
- grad_sdk-0.2.0a1/grad/__init__.py +206 -0
- grad_sdk-0.2.0a1/grad/_config.py +203 -0
- grad_sdk-0.2.0a1/grad/_errors.py +461 -0
- grad_sdk-0.2.0a1/grad/_format.py +175 -0
- grad_sdk-0.2.0a1/grad/_generated/__init__.py +4 -0
- grad_sdk-0.2.0a1/grad/_generated/client.py +1758 -0
- grad_sdk-0.2.0a1/grad/_helpers.py +552 -0
- grad_sdk-0.2.0a1/grad/_models.py +1161 -0
- grad_sdk-0.2.0a1/grad/_resources.py +1080 -0
- grad_sdk-0.2.0a1/grad/_transport.py +386 -0
- grad_sdk-0.2.0a1/grad/_version.py +3 -0
- grad_sdk-0.2.0a1/grad/client.py +113 -0
- grad_sdk-0.2.0a1/grad/environments.py +257 -0
- grad_sdk-0.2.0a1/grad/py.typed +0 -0
- grad_sdk-0.2.0a1/grad/recipes.py +684 -0
- grad_sdk-0.2.0a1/grad/records.py +411 -0
- grad_sdk-0.2.0a1/grad/rubrics.py +355 -0
- grad_sdk-0.2.0a1/grad/sources.py +138 -0
- grad_sdk-0.2.0a1/grad/specs.py +402 -0
- grad_sdk-0.2.0a1/grad/validators.py +217 -0
- grad_sdk-0.2.0a1/grad_sdk.egg-info/PKG-INFO +139 -0
- grad_sdk-0.2.0a1/grad_sdk.egg-info/SOURCES.txt +40 -0
- grad_sdk-0.2.0a1/grad_sdk.egg-info/dependency_links.txt +1 -0
- grad_sdk-0.2.0a1/grad_sdk.egg-info/requires.txt +5 -0
- grad_sdk-0.2.0a1/grad_sdk.egg-info/top_level.txt +1 -0
- grad_sdk-0.2.0a1/pyproject.toml +60 -0
- grad_sdk-0.2.0a1/setup.cfg +4 -0
- grad_sdk-0.2.0a1/tests/test_config.py +170 -0
- grad_sdk-0.2.0a1/tests/test_downloads.py +255 -0
- grad_sdk-0.2.0a1/tests/test_environments.py +90 -0
- grad_sdk-0.2.0a1/tests/test_live.py +427 -0
- grad_sdk-0.2.0a1/tests/test_live_sources.py +221 -0
- grad_sdk-0.2.0a1/tests/test_pagination.py +121 -0
- grad_sdk-0.2.0a1/tests/test_parity.py +212 -0
- grad_sdk-0.2.0a1/tests/test_recipes.py +395 -0
- grad_sdk-0.2.0a1/tests/test_resources.py +865 -0
- grad_sdk-0.2.0a1/tests/test_rubrics.py +244 -0
- grad_sdk-0.2.0a1/tests/test_sources.py +165 -0
- grad_sdk-0.2.0a1/tests/test_transport.py +322 -0
grad_sdk-0.2.0a1/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Gradiated
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: grad-sdk
|
|
3
|
+
Version: 0.2.0a1
|
|
4
|
+
Summary: Python SDK for the Gradiated training platform: datasets, managed fine-tuning runs, evals, artifacts and deployments.
|
|
5
|
+
Author: Gradiated
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://gradiated.com
|
|
8
|
+
Project-URL: Documentation, https://gradiated.com/docs/training
|
|
9
|
+
Project-URL: Repository, https://github.com/Gradiated/grad
|
|
10
|
+
Project-URL: Changelog, https://github.com/Gradiated/grad/blob/main/CHANGELOG.md
|
|
11
|
+
Keywords: llm,fine-tuning,lora,peft,evals,routing,gradiated
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.11
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Requires-Dist: httpx<1,>=0.27
|
|
27
|
+
Provides-Extra: dev
|
|
28
|
+
Requires-Dist: coverage>=7.6; extra == "dev"
|
|
29
|
+
Requires-Dist: mypy>=1.13; extra == "dev"
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# grad-sdk (Python)
|
|
33
|
+
|
|
34
|
+
The Python SDK for the Gradiated training platform: push datasets, preview and launch managed
|
|
35
|
+
fine-tuning runs, evaluate models, download PEFT adapters and deploy them on Gradiated Cloud.
|
|
36
|
+
|
|
37
|
+
- Python 3.11+, one dependency (`httpx`); a blocking `Grad` client (from asyncio, call it via `asyncio.to_thread`).
|
|
38
|
+
- Typed objects with a `.raw` escape hatch, `py.typed`, typed errors, retries with backoff.
|
|
39
|
+
- Works against Gradiated Cloud or a self-hosted `grad-server`.
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pip install grad-sdk
|
|
43
|
+
export GRADIATED_API_KEY=grad_...
|
|
44
|
+
# Self-hosted server: export GRADIATED_BASE_URL=http://localhost:8787
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Quickstart
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from grad import Grad
|
|
51
|
+
from grad.recipes import SFTRecipe
|
|
52
|
+
|
|
53
|
+
client = Grad() # reads GRADIATED_API_KEY and GRADIATED_BASE_URL
|
|
54
|
+
|
|
55
|
+
dataset = client.datasets.push("sql-quickstart", [
|
|
56
|
+
{"messages": [
|
|
57
|
+
{"role": "user", "content": "Count active users from yesterday."},
|
|
58
|
+
{"role": "assistant", "content": "SELECT count(*) FROM users WHERE active_at >= current_date - 1;"},
|
|
59
|
+
]},
|
|
60
|
+
{"messages": [
|
|
61
|
+
{"role": "user", "content": "Total revenue by plan this month."},
|
|
62
|
+
{"role": "assistant", "content": "SELECT plan, sum(amount_usd) FROM invoices GROUP BY plan;"},
|
|
63
|
+
]},
|
|
64
|
+
])
|
|
65
|
+
|
|
66
|
+
recipe = SFTRecipe(model="qwen/qwen3-8b")
|
|
67
|
+
|
|
68
|
+
# $0 preview: resolved defaults, warnings, tokens and cost
|
|
69
|
+
print(client.runs.plan(dataset=dataset, name="sql-helper", recipe=recipe))
|
|
70
|
+
|
|
71
|
+
run = client.runs.create(dataset=dataset, name="sql-helper", recipe=recipe, max_cost_usd=5).wait()
|
|
72
|
+
print(run.status, run.artifact)
|
|
73
|
+
|
|
74
|
+
# Self-hosted: download the PEFT LoRA and serve it with vLLM or SGLang.
|
|
75
|
+
# Gradiated Cloud: run.deploy() serves it behind a stable name.
|
|
76
|
+
run.artifact.download("./sql-helper-bundle.grad.tar.gz", format="bundle")
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
`run.artifact.download("./sql-helper")` (the default `format="peft"`) extracts a verified PEFT
|
|
80
|
+
directory (`adapter_config.json` + `adapter_model.safetensors`) that `vllm serve <base>
|
|
81
|
+
--enable-lora --lora-modules sql-helper=./sql-helper` loads directly.
|
|
82
|
+
|
|
83
|
+
## Configuration
|
|
84
|
+
|
|
85
|
+
Every SDK and the CLI resolve configuration the same way (highest first):
|
|
86
|
+
|
|
87
|
+
1. explicit arguments: `Grad(api_key=..., base_url=...)`;
|
|
88
|
+
2. the selected profile: `Grad(profile=...)` or `GRADIATED_PROFILE` (e.g. `local` after `grad local up`);
|
|
89
|
+
3. `GRADIATED_API_KEY` / `GRADIATED_BASE_URL`;
|
|
90
|
+
4. the `default` profile in `$XDG_CONFIG_HOME/gradiated/config.json` (written by `grad login`);
|
|
91
|
+
5. `https://api.gradiated.com`.
|
|
92
|
+
|
|
93
|
+
A key saved in a profile is only sent to that profile's base URL, and a selected profile that
|
|
94
|
+
doesn't exist is an error. Without a key for a non-loopback server, `Grad()` raises
|
|
95
|
+
`GradConfigError` before sending anything (`api_key=""` talks to a server without
|
|
96
|
+
authentication). A trailing `/v1` on the base URL is dropped with a warning. Also: `timeout=`
|
|
97
|
+
(per request), `max_retries=` (default 2).
|
|
98
|
+
|
|
99
|
+
## Errors
|
|
100
|
+
|
|
101
|
+
Every error subclasses `grad.GradError`. HTTP errors are `grad.GradAPIError` subclasses carrying
|
|
102
|
+
`status`, `code`, `detail`, `request_id`, the method and URL: `AuthenticationError` (401),
|
|
103
|
+
`PermissionDeniedError` (403), `NotFoundError` (404), `ConflictError` (409), `ValidationError`
|
|
104
|
+
(422, with field `errors`), `RateLimitError` (429), `DeployUnavailableError` and
|
|
105
|
+
`InferenceUnavailableError` (501), `ServerError` (5xx). Network failures raise
|
|
106
|
+
`APIConnectionError` / `APITimeoutError`; `wait()` raises `RunFailedError` (code `run_failed`,
|
|
107
|
+
`run_cancelled` or `run_stopped_budget`: anything but `completed`), `EvalFailedError`,
|
|
108
|
+
`ImportFailedError` or `WaitTimeoutError`; a list endpoint that repeats its cursor raises
|
|
109
|
+
`PaginationLoopError` instead of looping. Features documented for later waves raise
|
|
110
|
+
`NotAvailableInV0Error` with an alternative.
|
|
111
|
+
|
|
112
|
+
## Continued training and idempotent calls
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
from grad import Grad
|
|
116
|
+
from grad.recipes import DPORecipe, SFTRecipe
|
|
117
|
+
|
|
118
|
+
client = Grad()
|
|
119
|
+
sft = client.runs.create(dataset="sql-sft", name="sql-helper", recipe=SFTRecipe()).wait()
|
|
120
|
+
dpo = client.runs.create(dataset="sql-prefs", name="sql-helper", recipe=DPORecipe(model=sft.artifact),
|
|
121
|
+
idempotency_key="sql-helper-dpo-1").wait()
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
`runs.create`, `evals.create` and `deploy` send a fresh `Idempotency-Key` per call (reused by
|
|
125
|
+
its retries); pass `idempotency_key=` to make a retry from another process return the first call's
|
|
126
|
+
result instead of starting a second run.
|
|
127
|
+
|
|
128
|
+
## Development
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
PYTHONPATH=sdks/python python3 -m unittest discover -s sdks/python/tests
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Unit tests use a scripted fake `httpx` transport and the shared wire fixtures in `tests/fixtures/wire`.
|
|
135
|
+
`test_live.py` runs these snippets against `tests/harness/stack.ts`; it skips unless
|
|
136
|
+
`server/api/node_modules` exists (`pnpm -C server/api install --frozen-lockfile`), and the Cloud
|
|
137
|
+
deploy flow also needs `GRAD_TRAINER_PYTHON` (a Python with torch, transformers and peft). The
|
|
138
|
+
transport in `grad/_generated/client.py` is generated from `spec/openapi.yaml` by
|
|
139
|
+
`node scripts/generate-sdks.mjs`.
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# grad-sdk (Python)
|
|
2
|
+
|
|
3
|
+
The Python SDK for the Gradiated training platform: push datasets, preview and launch managed
|
|
4
|
+
fine-tuning runs, evaluate models, download PEFT adapters and deploy them on Gradiated Cloud.
|
|
5
|
+
|
|
6
|
+
- Python 3.11+, one dependency (`httpx`); a blocking `Grad` client (from asyncio, call it via `asyncio.to_thread`).
|
|
7
|
+
- Typed objects with a `.raw` escape hatch, `py.typed`, typed errors, retries with backoff.
|
|
8
|
+
- Works against Gradiated Cloud or a self-hosted `grad-server`.
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
pip install grad-sdk
|
|
12
|
+
export GRADIATED_API_KEY=grad_...
|
|
13
|
+
# Self-hosted server: export GRADIATED_BASE_URL=http://localhost:8787
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Quickstart
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
from grad import Grad
|
|
20
|
+
from grad.recipes import SFTRecipe
|
|
21
|
+
|
|
22
|
+
client = Grad() # reads GRADIATED_API_KEY and GRADIATED_BASE_URL
|
|
23
|
+
|
|
24
|
+
dataset = client.datasets.push("sql-quickstart", [
|
|
25
|
+
{"messages": [
|
|
26
|
+
{"role": "user", "content": "Count active users from yesterday."},
|
|
27
|
+
{"role": "assistant", "content": "SELECT count(*) FROM users WHERE active_at >= current_date - 1;"},
|
|
28
|
+
]},
|
|
29
|
+
{"messages": [
|
|
30
|
+
{"role": "user", "content": "Total revenue by plan this month."},
|
|
31
|
+
{"role": "assistant", "content": "SELECT plan, sum(amount_usd) FROM invoices GROUP BY plan;"},
|
|
32
|
+
]},
|
|
33
|
+
])
|
|
34
|
+
|
|
35
|
+
recipe = SFTRecipe(model="qwen/qwen3-8b")
|
|
36
|
+
|
|
37
|
+
# $0 preview: resolved defaults, warnings, tokens and cost
|
|
38
|
+
print(client.runs.plan(dataset=dataset, name="sql-helper", recipe=recipe))
|
|
39
|
+
|
|
40
|
+
run = client.runs.create(dataset=dataset, name="sql-helper", recipe=recipe, max_cost_usd=5).wait()
|
|
41
|
+
print(run.status, run.artifact)
|
|
42
|
+
|
|
43
|
+
# Self-hosted: download the PEFT LoRA and serve it with vLLM or SGLang.
|
|
44
|
+
# Gradiated Cloud: run.deploy() serves it behind a stable name.
|
|
45
|
+
run.artifact.download("./sql-helper-bundle.grad.tar.gz", format="bundle")
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
`run.artifact.download("./sql-helper")` (the default `format="peft"`) extracts a verified PEFT
|
|
49
|
+
directory (`adapter_config.json` + `adapter_model.safetensors`) that `vllm serve <base>
|
|
50
|
+
--enable-lora --lora-modules sql-helper=./sql-helper` loads directly.
|
|
51
|
+
|
|
52
|
+
## Configuration
|
|
53
|
+
|
|
54
|
+
Every SDK and the CLI resolve configuration the same way (highest first):
|
|
55
|
+
|
|
56
|
+
1. explicit arguments: `Grad(api_key=..., base_url=...)`;
|
|
57
|
+
2. the selected profile: `Grad(profile=...)` or `GRADIATED_PROFILE` (e.g. `local` after `grad local up`);
|
|
58
|
+
3. `GRADIATED_API_KEY` / `GRADIATED_BASE_URL`;
|
|
59
|
+
4. the `default` profile in `$XDG_CONFIG_HOME/gradiated/config.json` (written by `grad login`);
|
|
60
|
+
5. `https://api.gradiated.com`.
|
|
61
|
+
|
|
62
|
+
A key saved in a profile is only sent to that profile's base URL, and a selected profile that
|
|
63
|
+
doesn't exist is an error. Without a key for a non-loopback server, `Grad()` raises
|
|
64
|
+
`GradConfigError` before sending anything (`api_key=""` talks to a server without
|
|
65
|
+
authentication). A trailing `/v1` on the base URL is dropped with a warning. Also: `timeout=`
|
|
66
|
+
(per request), `max_retries=` (default 2).
|
|
67
|
+
|
|
68
|
+
## Errors
|
|
69
|
+
|
|
70
|
+
Every error subclasses `grad.GradError`. HTTP errors are `grad.GradAPIError` subclasses carrying
|
|
71
|
+
`status`, `code`, `detail`, `request_id`, the method and URL: `AuthenticationError` (401),
|
|
72
|
+
`PermissionDeniedError` (403), `NotFoundError` (404), `ConflictError` (409), `ValidationError`
|
|
73
|
+
(422, with field `errors`), `RateLimitError` (429), `DeployUnavailableError` and
|
|
74
|
+
`InferenceUnavailableError` (501), `ServerError` (5xx). Network failures raise
|
|
75
|
+
`APIConnectionError` / `APITimeoutError`; `wait()` raises `RunFailedError` (code `run_failed`,
|
|
76
|
+
`run_cancelled` or `run_stopped_budget`: anything but `completed`), `EvalFailedError`,
|
|
77
|
+
`ImportFailedError` or `WaitTimeoutError`; a list endpoint that repeats its cursor raises
|
|
78
|
+
`PaginationLoopError` instead of looping. Features documented for later waves raise
|
|
79
|
+
`NotAvailableInV0Error` with an alternative.
|
|
80
|
+
|
|
81
|
+
## Continued training and idempotent calls
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
from grad import Grad
|
|
85
|
+
from grad.recipes import DPORecipe, SFTRecipe
|
|
86
|
+
|
|
87
|
+
client = Grad()
|
|
88
|
+
sft = client.runs.create(dataset="sql-sft", name="sql-helper", recipe=SFTRecipe()).wait()
|
|
89
|
+
dpo = client.runs.create(dataset="sql-prefs", name="sql-helper", recipe=DPORecipe(model=sft.artifact),
|
|
90
|
+
idempotency_key="sql-helper-dpo-1").wait()
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
`runs.create`, `evals.create` and `deploy` send a fresh `Idempotency-Key` per call (reused by
|
|
94
|
+
its retries); pass `idempotency_key=` to make a retry from another process return the first call's
|
|
95
|
+
result instead of starting a second run.
|
|
96
|
+
|
|
97
|
+
## Development
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
PYTHONPATH=sdks/python python3 -m unittest discover -s sdks/python/tests
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Unit tests use a scripted fake `httpx` transport and the shared wire fixtures in `tests/fixtures/wire`.
|
|
104
|
+
`test_live.py` runs these snippets against `tests/harness/stack.ts`; it skips unless
|
|
105
|
+
`server/api/node_modules` exists (`pnpm -C server/api install --frozen-lockfile`), and the Cloud
|
|
106
|
+
deploy flow also needs `GRAD_TRAINER_PYTHON` (a Python with torch, transformers and peft). The
|
|
107
|
+
transport in `grad/_generated/client.py` is generated from `spec/openapi.yaml` by
|
|
108
|
+
`node scripts/generate-sdks.mjs`.
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""grad-sdk: the Python SDK for the Gradiated training platform.
|
|
2
|
+
|
|
3
|
+
from grad import Grad
|
|
4
|
+
from grad.recipes import SFTRecipe
|
|
5
|
+
|
|
6
|
+
client = Grad() # reads GRADIATED_API_KEY (and GRADIATED_BASE_URL)
|
|
7
|
+
dataset = client.datasets.push("sql-quickstart", records)
|
|
8
|
+
print(client.runs.plan(dataset=dataset, name="sql-helper", recipe=SFTRecipe()))
|
|
9
|
+
run = client.runs.create(dataset=dataset, name="sql-helper", recipe=SFTRecipe(), max_cost_usd=5).wait()
|
|
10
|
+
run.download("./sql-helper") # PEFT LoRA for vLLM / SGLang, or run.deploy() on Gradiated Cloud
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from . import validators
|
|
14
|
+
from ._config import DEFAULT_BASE_URL, ResolvedConfig, default_config_path
|
|
15
|
+
from ._errors import (
|
|
16
|
+
APIConnectionError,
|
|
17
|
+
APITimeoutError,
|
|
18
|
+
AuthenticationError,
|
|
19
|
+
BadRequestError,
|
|
20
|
+
ChecksumMismatchError,
|
|
21
|
+
ConflictError,
|
|
22
|
+
DeployUnavailableError,
|
|
23
|
+
EvalFailedError,
|
|
24
|
+
FeatureUnavailableError,
|
|
25
|
+
FieldError,
|
|
26
|
+
GradAPIError,
|
|
27
|
+
GradApiError,
|
|
28
|
+
GradConfigError,
|
|
29
|
+
GradError,
|
|
30
|
+
ImportFailedError,
|
|
31
|
+
InferenceUnavailableError,
|
|
32
|
+
InvalidResponseError,
|
|
33
|
+
JobFailedError,
|
|
34
|
+
NotAvailableInV0Error,
|
|
35
|
+
NotFoundError,
|
|
36
|
+
PaginationLoopError,
|
|
37
|
+
PayloadTooLargeError,
|
|
38
|
+
PermissionDeniedError,
|
|
39
|
+
RateLimitError,
|
|
40
|
+
RunFailedError,
|
|
41
|
+
ScorerError,
|
|
42
|
+
ServerError,
|
|
43
|
+
UnexpectedRedirectError,
|
|
44
|
+
UnsafeArchiveError,
|
|
45
|
+
ValidationError,
|
|
46
|
+
WaitTimeoutError,
|
|
47
|
+
)
|
|
48
|
+
from ._models import (
|
|
49
|
+
ApiKey,
|
|
50
|
+
Artifact,
|
|
51
|
+
AttrDict,
|
|
52
|
+
Checkpoint,
|
|
53
|
+
CreatedApiKey,
|
|
54
|
+
Dataset,
|
|
55
|
+
DatasetScoring,
|
|
56
|
+
Deployment,
|
|
57
|
+
DeploymentStatus,
|
|
58
|
+
Eval,
|
|
59
|
+
EvalFailures,
|
|
60
|
+
EvalModelSummary,
|
|
61
|
+
EvalOutput,
|
|
62
|
+
EvalPlan,
|
|
63
|
+
EvalReport,
|
|
64
|
+
EvalResult,
|
|
65
|
+
ImportJob,
|
|
66
|
+
MetricPoint,
|
|
67
|
+
Model,
|
|
68
|
+
Page,
|
|
69
|
+
Plan,
|
|
70
|
+
RenderPreview,
|
|
71
|
+
RouterParetoSummary,
|
|
72
|
+
Run,
|
|
73
|
+
SecretRef,
|
|
74
|
+
Source,
|
|
75
|
+
UsageRecord,
|
|
76
|
+
)
|
|
77
|
+
from ._version import __version__
|
|
78
|
+
from .client import Grad
|
|
79
|
+
from .environments import (
|
|
80
|
+
Action,
|
|
81
|
+
Environment,
|
|
82
|
+
Observation,
|
|
83
|
+
StepOutcome,
|
|
84
|
+
ToolCall,
|
|
85
|
+
ToolsEnvironment,
|
|
86
|
+
environments,
|
|
87
|
+
)
|
|
88
|
+
from .recipes import (
|
|
89
|
+
CartridgeRecipe,
|
|
90
|
+
DecisionModelRecipe,
|
|
91
|
+
DistillRecipe,
|
|
92
|
+
DPORecipe,
|
|
93
|
+
EmbeddingRecipe,
|
|
94
|
+
GRPORecipe,
|
|
95
|
+
RewardModelRecipe,
|
|
96
|
+
RouterRecipe,
|
|
97
|
+
SFTRecipe,
|
|
98
|
+
)
|
|
99
|
+
from .records import Context, PreferencePair, Record, Task, Trajectory, Triplet
|
|
100
|
+
from .rubrics import Judge, Rubric, Scorer, StatefulScorer
|
|
101
|
+
from . import sources
|
|
102
|
+
from .specs import adapters, advantages, heads, loggers, losses, mergers, optim, pooling, splits
|
|
103
|
+
from .recipes import EvalSpec
|
|
104
|
+
|
|
105
|
+
__all__ = [
|
|
106
|
+
"APIConnectionError",
|
|
107
|
+
"APITimeoutError",
|
|
108
|
+
"Action",
|
|
109
|
+
"ApiKey",
|
|
110
|
+
"Artifact",
|
|
111
|
+
"AttrDict",
|
|
112
|
+
"AuthenticationError",
|
|
113
|
+
"BadRequestError",
|
|
114
|
+
"CartridgeRecipe",
|
|
115
|
+
"Checkpoint",
|
|
116
|
+
"ChecksumMismatchError",
|
|
117
|
+
"ConflictError",
|
|
118
|
+
"Context",
|
|
119
|
+
"CreatedApiKey",
|
|
120
|
+
"DEFAULT_BASE_URL",
|
|
121
|
+
"DPORecipe",
|
|
122
|
+
"Dataset",
|
|
123
|
+
"DatasetScoring",
|
|
124
|
+
"DecisionModelRecipe",
|
|
125
|
+
"DeployUnavailableError",
|
|
126
|
+
"Deployment",
|
|
127
|
+
"DeploymentStatus",
|
|
128
|
+
"DistillRecipe",
|
|
129
|
+
"EmbeddingRecipe",
|
|
130
|
+
"Environment",
|
|
131
|
+
"Eval",
|
|
132
|
+
"EvalFailedError",
|
|
133
|
+
"EvalFailures",
|
|
134
|
+
"EvalModelSummary",
|
|
135
|
+
"EvalOutput",
|
|
136
|
+
"EvalPlan",
|
|
137
|
+
"EvalReport",
|
|
138
|
+
"EvalResult",
|
|
139
|
+
"FeatureUnavailableError",
|
|
140
|
+
"FieldError",
|
|
141
|
+
"GRPORecipe",
|
|
142
|
+
"Grad",
|
|
143
|
+
"GradAPIError",
|
|
144
|
+
"GradApiError",
|
|
145
|
+
"GradConfigError",
|
|
146
|
+
"GradError",
|
|
147
|
+
"ImportFailedError",
|
|
148
|
+
"ImportJob",
|
|
149
|
+
"InferenceUnavailableError",
|
|
150
|
+
"InvalidResponseError",
|
|
151
|
+
"JobFailedError",
|
|
152
|
+
"Judge",
|
|
153
|
+
"MetricPoint",
|
|
154
|
+
"Model",
|
|
155
|
+
"NotAvailableInV0Error",
|
|
156
|
+
"NotFoundError",
|
|
157
|
+
"PaginationLoopError",
|
|
158
|
+
"Observation",
|
|
159
|
+
"Page",
|
|
160
|
+
"PayloadTooLargeError",
|
|
161
|
+
"PermissionDeniedError",
|
|
162
|
+
"Plan",
|
|
163
|
+
"PreferencePair",
|
|
164
|
+
"RateLimitError",
|
|
165
|
+
"Record",
|
|
166
|
+
"RenderPreview",
|
|
167
|
+
"ResolvedConfig",
|
|
168
|
+
"RewardModelRecipe",
|
|
169
|
+
"RouterRecipe",
|
|
170
|
+
"Rubric",
|
|
171
|
+
"Run",
|
|
172
|
+
"SecretRef",
|
|
173
|
+
"Source",
|
|
174
|
+
"UsageRecord",
|
|
175
|
+
"RunFailedError",
|
|
176
|
+
"SFTRecipe",
|
|
177
|
+
"Scorer",
|
|
178
|
+
"ScorerError",
|
|
179
|
+
"ServerError",
|
|
180
|
+
"StatefulScorer",
|
|
181
|
+
"StepOutcome",
|
|
182
|
+
"Task",
|
|
183
|
+
"ToolCall",
|
|
184
|
+
"ToolsEnvironment",
|
|
185
|
+
"Trajectory",
|
|
186
|
+
"Triplet",
|
|
187
|
+
"UnexpectedRedirectError",
|
|
188
|
+
"UnsafeArchiveError",
|
|
189
|
+
"ValidationError",
|
|
190
|
+
"WaitTimeoutError",
|
|
191
|
+
"__version__",
|
|
192
|
+
"adapters",
|
|
193
|
+
"advantages",
|
|
194
|
+
"default_config_path",
|
|
195
|
+
"environments",
|
|
196
|
+
"heads",
|
|
197
|
+
"loggers",
|
|
198
|
+
"EvalSpec",
|
|
199
|
+
"losses",
|
|
200
|
+
"mergers",
|
|
201
|
+
"optim",
|
|
202
|
+
"pooling",
|
|
203
|
+
"sources",
|
|
204
|
+
"splits",
|
|
205
|
+
"validators",
|
|
206
|
+
]
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""Client configuration: arguments > selected profile > environment > default profile > Cloud.
|
|
2
|
+
|
|
3
|
+
* ``GRADIATED_API_KEY``, ``GRADIATED_BASE_URL`` and ``GRADIATED_PROFILE`` are read from the
|
|
4
|
+
environment; a profile selected by ``GRADIATED_PROFILE`` wins over the other two.
|
|
5
|
+
* ``grad login`` writes ``$XDG_CONFIG_HOME/gradiated/config.json`` (default
|
|
6
|
+
``~/.config/gradiated/config.json``) as ``{"profiles": {"default": {"base_url", "api_key"}}}``;
|
|
7
|
+
it is used for whatever the arguments and the environment leave unset.
|
|
8
|
+
* The default base URL is Gradiated Cloud, ``https://api.gradiated.com``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import ipaddress
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import urllib.parse
|
|
17
|
+
import warnings
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any, Mapping
|
|
21
|
+
|
|
22
|
+
from ._errors import GradConfigError
|
|
23
|
+
|
|
24
|
+
DEFAULT_BASE_URL = "https://api.gradiated.com"
|
|
25
|
+
ENV_API_KEY = "GRADIATED_API_KEY"
|
|
26
|
+
ENV_BASE_URL = "GRADIATED_BASE_URL"
|
|
27
|
+
ENV_PROFILE = "GRADIATED_PROFILE"
|
|
28
|
+
DEFAULT_PROFILE = "default"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def default_config_path(env: Mapping[str, str] | None = None) -> Path:
|
|
32
|
+
"""Location of the ``grad login`` config file for this environment."""
|
|
33
|
+
env = os.environ if env is None else env
|
|
34
|
+
base = env.get("XDG_CONFIG_HOME") or str(Path(env.get("HOME") or Path.home()) / ".config")
|
|
35
|
+
return Path(base) / "gradiated" / "config.json"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def normalize_base_url(raw: str) -> str:
|
|
39
|
+
"""Validate a base URL (``http(s)://host[:port][/prefix]``) and strip the trailing slash."""
|
|
40
|
+
text = raw.strip()
|
|
41
|
+
parsed = urllib.parse.urlsplit(text)
|
|
42
|
+
if parsed.scheme not in ("http", "https") or not parsed.hostname:
|
|
43
|
+
raise GradConfigError(
|
|
44
|
+
f"Invalid base_url {raw!r}: expected http(s)://host[:port], e.g. https://api.gradiated.com "
|
|
45
|
+
"or http://localhost:8787."
|
|
46
|
+
)
|
|
47
|
+
if parsed.query or parsed.fragment or parsed.username or parsed.password:
|
|
48
|
+
raise GradConfigError(f"Invalid base_url {raw!r}: it must not contain credentials, a query or a fragment.")
|
|
49
|
+
try:
|
|
50
|
+
parsed.port # noqa: B018 - validates the port number
|
|
51
|
+
except ValueError as exc:
|
|
52
|
+
raise GradConfigError(f"Invalid base_url {raw!r}: {exc}.") from None
|
|
53
|
+
return urllib.parse.urlunsplit((parsed.scheme, parsed.netloc, parsed.path.rstrip("/"), "", ""))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def is_loopback(base_url: str) -> bool:
|
|
57
|
+
"""True when ``base_url`` points at this machine (local stacks often run without auth)."""
|
|
58
|
+
host = urllib.parse.urlsplit(base_url).hostname or ""
|
|
59
|
+
if host == "localhost" or host.endswith(".localhost"):
|
|
60
|
+
return True
|
|
61
|
+
try:
|
|
62
|
+
return ipaddress.ip_address(host).is_loopback
|
|
63
|
+
except ValueError:
|
|
64
|
+
return False
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(frozen=True)
|
|
68
|
+
class ResolvedConfig:
|
|
69
|
+
"""The configuration a client ended up with, and where each value came from."""
|
|
70
|
+
|
|
71
|
+
base_url: str
|
|
72
|
+
api_key: str | None
|
|
73
|
+
profile: str
|
|
74
|
+
sources: dict[str, str] = field(default_factory=dict)
|
|
75
|
+
|
|
76
|
+
def __repr__(self) -> str:
|
|
77
|
+
key = "None" if self.api_key is None else f"'{_mask(self.api_key)}'"
|
|
78
|
+
return f"ResolvedConfig(base_url={self.base_url!r}, api_key={key}, profile={self.profile!r})"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _mask(secret: str) -> str:
|
|
82
|
+
return "" if not secret else f"{secret[:6]}…" if len(secret) > 10 else "…"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _load_profile(path: Path, profile: str, *, required: bool) -> dict[str, Any]:
|
|
86
|
+
try:
|
|
87
|
+
text = path.read_text(encoding="utf-8")
|
|
88
|
+
except FileNotFoundError:
|
|
89
|
+
if required:
|
|
90
|
+
raise GradConfigError(f"Profile '{profile}' was requested but {path} does not exist; run `grad login`.") from None
|
|
91
|
+
return {}
|
|
92
|
+
except OSError as exc:
|
|
93
|
+
raise GradConfigError(f"Cannot read grad config file {path}: {exc}") from None
|
|
94
|
+
try:
|
|
95
|
+
data = json.loads(text)
|
|
96
|
+
except ValueError as exc:
|
|
97
|
+
raise GradConfigError(f"Malformed grad config file {path}: {exc}. Fix it or run `grad login` again.") from None
|
|
98
|
+
profiles = data.get("profiles") if isinstance(data, dict) else None
|
|
99
|
+
if not isinstance(profiles, dict):
|
|
100
|
+
raise GradConfigError(f'Malformed grad config file {path}: expected {{"profiles": {{"{profile}": {{...}}}}}}.')
|
|
101
|
+
entry = profiles.get(profile)
|
|
102
|
+
if entry is None:
|
|
103
|
+
if required:
|
|
104
|
+
known = ", ".join(sorted(str(k) for k in profiles)) or "none"
|
|
105
|
+
raise GradConfigError(f"Profile '{profile}' is not in {path} (profiles: {known}).")
|
|
106
|
+
return {}
|
|
107
|
+
if not isinstance(entry, dict):
|
|
108
|
+
raise GradConfigError(f"Malformed profile '{profile}' in {path}: expected an object.")
|
|
109
|
+
return entry
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def missing_key_message(base_url: str) -> str:
|
|
113
|
+
"""The error every SDK and the CLI give when no API key is configured for a remote server."""
|
|
114
|
+
return (
|
|
115
|
+
f"No API key for {base_url}: run `grad login`, set {ENV_API_KEY}, "
|
|
116
|
+
f"or export {ENV_PROFILE}=local to use a `grad local up` stack."
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def strip_api_suffix(base_url: str) -> str:
|
|
121
|
+
"""Drop a trailing ``/v1`` (the SDK adds it), warning once so the config gets fixed."""
|
|
122
|
+
if base_url.endswith("/v1"):
|
|
123
|
+
warnings.warn(
|
|
124
|
+
f"base_url {base_url!r} ends in /v1; the SDK adds /v1 itself, so it was dropped.",
|
|
125
|
+
stacklevel=4,
|
|
126
|
+
)
|
|
127
|
+
return base_url[: -len("/v1")]
|
|
128
|
+
return base_url
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def resolve_config(
|
|
132
|
+
*,
|
|
133
|
+
api_key: str | None = None,
|
|
134
|
+
base_url: str | None = None,
|
|
135
|
+
profile: str | None = None,
|
|
136
|
+
config_path: str | os.PathLike[str] | None = None,
|
|
137
|
+
env: Mapping[str, str] | None = None,
|
|
138
|
+
require_key: bool = True,
|
|
139
|
+
) -> ResolvedConfig:
|
|
140
|
+
"""Resolve ``base_url`` and ``api_key``; every SDK and the CLI use this precedence.
|
|
141
|
+
|
|
142
|
+
1. explicit arguments (``api_key=``, ``base_url=``);
|
|
143
|
+
2. an explicitly selected profile (``profile=`` or ``GRADIATED_PROFILE``);
|
|
144
|
+
3. ``GRADIATED_API_KEY`` / ``GRADIATED_BASE_URL``;
|
|
145
|
+
4. the ``default`` profile of the ``grad login`` config file;
|
|
146
|
+
5. ``https://api.gradiated.com``.
|
|
147
|
+
|
|
148
|
+
A key saved in a profile is only sent to that profile's own base URL. A selected
|
|
149
|
+
profile that does not exist is an error. ``api_key=""`` explicitly disables
|
|
150
|
+
authentication (for auth-less servers). When no key is found and the server is not
|
|
151
|
+
on loopback, this raises :class:`GradConfigError` before any request is sent.
|
|
152
|
+
"""
|
|
153
|
+
env = os.environ if env is None else env
|
|
154
|
+
sources: dict[str, str] = {}
|
|
155
|
+
|
|
156
|
+
explicit = profile or env.get(ENV_PROFILE) or None
|
|
157
|
+
name = explicit or DEFAULT_PROFILE
|
|
158
|
+
path = Path(config_path) if config_path is not None else default_config_path(env)
|
|
159
|
+
covered = (base_url is not None or bool(env.get(ENV_BASE_URL))) and (api_key is not None or bool(env.get(ENV_API_KEY)))
|
|
160
|
+
entry = {} if covered and explicit is None else _load_profile(path, name, required=explicit is not None)
|
|
161
|
+
file_url = entry.get("base_url") if isinstance(entry.get("base_url"), str) and entry.get("base_url") else None
|
|
162
|
+
file_key = entry.get("api_key") if isinstance(entry.get("api_key"), str) and entry.get("api_key") else None
|
|
163
|
+
file_src = f"config:{path}#{name}"
|
|
164
|
+
|
|
165
|
+
resolved_url: str | None = None
|
|
166
|
+
if base_url is not None:
|
|
167
|
+
resolved_url, sources["base_url"] = base_url, "argument"
|
|
168
|
+
elif explicit is not None and file_url:
|
|
169
|
+
resolved_url, sources["base_url"] = file_url, file_src
|
|
170
|
+
elif env.get(ENV_BASE_URL):
|
|
171
|
+
resolved_url, sources["base_url"] = env[ENV_BASE_URL], f"env:{ENV_BASE_URL}"
|
|
172
|
+
elif file_url:
|
|
173
|
+
resolved_url, sources["base_url"] = file_url, file_src
|
|
174
|
+
else:
|
|
175
|
+
resolved_url, sources["base_url"] = DEFAULT_BASE_URL, "default"
|
|
176
|
+
normalized = strip_api_suffix(normalize_base_url(resolved_url))
|
|
177
|
+
|
|
178
|
+
# A saved key belongs to its profile's server: never send it anywhere else.
|
|
179
|
+
owner = strip_api_suffix(normalize_base_url(file_url)) if file_url else DEFAULT_BASE_URL
|
|
180
|
+
usable_file_key = file_key if file_key and owner == normalized else None
|
|
181
|
+
|
|
182
|
+
resolved_key: str | None = None
|
|
183
|
+
if api_key is not None:
|
|
184
|
+
resolved_key, sources["api_key"] = api_key, "argument"
|
|
185
|
+
elif explicit is not None and usable_file_key:
|
|
186
|
+
resolved_key, sources["api_key"] = usable_file_key, file_src
|
|
187
|
+
elif env.get(ENV_API_KEY):
|
|
188
|
+
resolved_key, sources["api_key"] = env[ENV_API_KEY], f"env:{ENV_API_KEY}"
|
|
189
|
+
elif usable_file_key:
|
|
190
|
+
resolved_key, sources["api_key"] = usable_file_key, file_src
|
|
191
|
+
|
|
192
|
+
if resolved_key is not None:
|
|
193
|
+
resolved_key = resolved_key.strip()
|
|
194
|
+
if any(ch.isspace() for ch in resolved_key):
|
|
195
|
+
raise GradConfigError("The API key contains whitespace; check GRADIATED_API_KEY.")
|
|
196
|
+
if not resolved_key:
|
|
197
|
+
if require_key and resolved_key is None and not is_loopback(normalized):
|
|
198
|
+
note = ""
|
|
199
|
+
if file_key and not usable_file_key:
|
|
200
|
+
note = f" (the key saved in profile '{name}' belongs to {owner}, so it was not sent)"
|
|
201
|
+
raise GradConfigError(missing_key_message(normalized) + note)
|
|
202
|
+
resolved_key = None
|
|
203
|
+
return ResolvedConfig(base_url=normalized, api_key=resolved_key, profile=name, sources=sources)
|