grad-sdk 0.2.0a1__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.
- grad/__init__.py +206 -0
- grad/_config.py +203 -0
- grad/_errors.py +461 -0
- grad/_format.py +175 -0
- grad/_generated/__init__.py +4 -0
- grad/_generated/client.py +1758 -0
- grad/_helpers.py +552 -0
- grad/_models.py +1161 -0
- grad/_resources.py +1080 -0
- grad/_transport.py +386 -0
- grad/_version.py +3 -0
- grad/client.py +113 -0
- grad/environments.py +257 -0
- grad/py.typed +0 -0
- grad/recipes.py +684 -0
- grad/records.py +411 -0
- grad/rubrics.py +355 -0
- grad/sources.py +138 -0
- grad/specs.py +402 -0
- grad/validators.py +217 -0
- grad_sdk-0.2.0a1.dist-info/METADATA +139 -0
- grad_sdk-0.2.0a1.dist-info/RECORD +25 -0
- grad_sdk-0.2.0a1.dist-info/WHEEL +5 -0
- grad_sdk-0.2.0a1.dist-info/licenses/LICENSE +21 -0
- grad_sdk-0.2.0a1.dist-info/top_level.txt +1 -0
grad/__init__.py
ADDED
|
@@ -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
|
+
]
|
grad/_config.py
ADDED
|
@@ -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)
|