@gradiated/grad 0.0.0-stage → 0.2.0-alpha.1
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.
- package/LICENSE +21 -0
- package/README.md +83 -2
- package/dist/client.d.ts +71 -0
- package/dist/client.js +188 -0
- package/dist/config.d.ts +21 -0
- package/dist/config.js +90 -0
- package/dist/core.d.ts +13 -0
- package/dist/core.js +1 -0
- package/dist/errors.d.ts +37 -0
- package/dist/errors.js +70 -0
- package/dist/generated/client.d.ts +532 -0
- package/dist/generated/client.js +596 -0
- package/dist/generated/index.d.ts +2 -0
- package/dist/generated/index.js +3 -0
- package/dist/generated/models.d.ts +998 -0
- package/dist/generated/models.js +9 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +16 -0
- package/dist/node/files.d.ts +26 -0
- package/dist/node/files.js +130 -0
- package/dist/pagination.d.ts +39 -0
- package/dist/pagination.js +73 -0
- package/dist/pending.d.ts +14 -0
- package/dist/pending.js +20 -0
- package/dist/polling.d.ts +25 -0
- package/dist/polling.js +63 -0
- package/dist/recipes.d.ts +220 -0
- package/dist/recipes.js +255 -0
- package/dist/resources/artifacts.d.ts +82 -0
- package/dist/resources/artifacts.js +122 -0
- package/dist/resources/datasets.d.ts +178 -0
- package/dist/resources/datasets.js +318 -0
- package/dist/resources/evals.d.ts +110 -0
- package/dist/resources/evals.js +258 -0
- package/dist/resources/misc.d.ts +31 -0
- package/dist/resources/misc.js +45 -0
- package/dist/resources/runs.d.ts +119 -0
- package/dist/resources/runs.js +245 -0
- package/dist/resources/sources.d.ts +118 -0
- package/dist/resources/sources.js +156 -0
- package/dist/rubrics.d.ts +87 -0
- package/dist/rubrics.js +167 -0
- package/dist/trajectory.d.ts +16 -0
- package/dist/trajectory.js +13 -0
- package/dist/transport.d.ts +229 -0
- package/dist/transport.js +678 -0
- package/package.json +53 -4
package/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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,84 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @gradiated/grad
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
TypeScript SDK for the Gradiated training platform: import traces, train
|
|
4
|
+
routers and fine-tunes, evaluate them, and deploy to Gradiated Cloud. ESM with
|
|
5
|
+
types, Node 20+. Browser-safe except the file helpers (`importFile`,
|
|
6
|
+
`download`, `Context.fromFile`), which load `node:fs` lazily.
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
npm install @gradiated/grad
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Quickstart
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { Grad, recipes } from "@gradiated/grad";
|
|
16
|
+
|
|
17
|
+
// GRADIATED_API_KEY and GRADIATED_BASE_URL, else the profile `grad login` wrote.
|
|
18
|
+
const grad = new Grad();
|
|
19
|
+
|
|
20
|
+
const dataset = await grad.datasets.create("support-prod");
|
|
21
|
+
await dataset.importFile("./support_traces.jsonl").wait();
|
|
22
|
+
|
|
23
|
+
const run = await grad.runs
|
|
24
|
+
.create({ dataset, name: "support-router", recipe: recipes.router() })
|
|
25
|
+
.wait({ onMetric: (m) => console.log(m.step, m.loss) });
|
|
26
|
+
|
|
27
|
+
await run.deploy(); // Cloud; a self-hosted server raises DeployUnavailableError
|
|
28
|
+
await grad.deployments.rollback("support-router"); // back to the previous artifact
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Self-hosted servers do not serve models: `artifact.download(dest)` and serve
|
|
32
|
+
the bundle yourself (vLLM, SGLang). Production feedback reaches training
|
|
33
|
+
through your observability tool and `grad sources`, not through this SDK.
|
|
34
|
+
|
|
35
|
+
Against a self-hosted server pass the URL explicitly:
|
|
36
|
+
`new Grad({ baseURL: "https://grad.internal.example", apiKey })`.
|
|
37
|
+
|
|
38
|
+
The same flow, nearly verbatim, runs in `test/live/*.live.test.ts` against a
|
|
39
|
+
real `grad-server` started by `tests/harness/stack.ts`.
|
|
40
|
+
|
|
41
|
+
## What is in the box
|
|
42
|
+
|
|
43
|
+
| Area | API |
|
|
44
|
+
| --- | --- |
|
|
45
|
+
| Datasets | `grad.datasets.create/get/list/push/records/render/fromHf`, `dataset.importFile(path).wait()` |
|
|
46
|
+
| Runs | `grad.runs.plan/create/get/list/cancel/resume`, `run.wait()`, `run.metrics({ follow: true })` (SSE with reconnect), `run.checkpoints()`, `checkpoint.promote()` |
|
|
47
|
+
| Recipes | `recipes.sft/dpo/router/decisionModel/cartridge/embedding/distill/rewardModel`, `rollouts`, `adapters`, `splits`, `Context` |
|
|
48
|
+
| Artifacts | `grad.artifacts.get/list/stream`, `artifact.download(dest)` (streams to disk, verifies SHA-256) |
|
|
49
|
+
| Deploy (Cloud) | `grad.deploy()` / `run.deploy()` / `artifact.deploy()` (= `grad.deployments.create`), `grad.deployments.get/list/rollback` |
|
|
50
|
+
| Evals | `grad.evals.plan/create/get/list`, `ev.wait()` (runs local scorers), `ev.summaryTable()`, `ev.failures().toDataset()`; `Rubric`, `Scorer`, `Judge`, `validators` |
|
|
51
|
+
| Keys, models | `grad.keys.create/list/revoke`, `grad.models.list()` |
|
|
52
|
+
| Low level | `grad.api`: one typed method per OpenAPI operation |
|
|
53
|
+
|
|
54
|
+
List calls return a `Paginator`: `await` it for the first page, `for await`
|
|
55
|
+
it for every item, or `.all()` (bounded, 100,000 items by default). A server
|
|
56
|
+
that repeats a cursor stops the listing with `PaginationLoopError`.
|
|
57
|
+
|
|
58
|
+
## Errors, retries, timeouts
|
|
59
|
+
|
|
60
|
+
Every error extends `GradError` (`status`, `code`, `requestId`). HTTP errors
|
|
61
|
+
map to `BadRequestError`, `AuthenticationError`, `PermissionDeniedError`,
|
|
62
|
+
`NotFoundError`, `ConflictError`, `ValidationError` (`fieldErrors`),
|
|
63
|
+
`RateLimitError`, `ServerError`, `DeployUnavailableError`,
|
|
64
|
+
`InferenceUnavailableError`; waits throw
|
|
65
|
+
`RunFailedError`, `EvalFailedError`, `ImportFailedError` or
|
|
66
|
+
`WaitTimeoutError`. Requests retry twice on 408/429/5xx with jittered
|
|
67
|
+
backoff that honours `Retry-After`; every POST carries one `Idempotency-Key`
|
|
68
|
+
(a UUIDv4, or `{ idempotencyKey }`) across its retries, so the server replays
|
|
69
|
+
the first response instead of running it twice. Redirects that leave the API
|
|
70
|
+
origin are refused, so the key is never sent elsewhere. `timeoutMs` (default
|
|
71
|
+
60 s) bounds each attempt; downloads and SSE streams use an idle timeout
|
|
72
|
+
instead. Every call accepts `{ signal }` to abort.
|
|
73
|
+
|
|
74
|
+
## Development
|
|
75
|
+
|
|
76
|
+
```sh
|
|
77
|
+
pnpm install --frozen-lockfile
|
|
78
|
+
pnpm check # tsc + unit tests with coverage (>= 90% lines)
|
|
79
|
+
pnpm test:live # needs `pnpm -C ../../server/api install`; skips otherwise
|
|
80
|
+
pnpm build
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`src/generated/` is written by `node scripts/generate-sdks.mjs` from
|
|
84
|
+
`spec/openapi.yaml`; do not edit it by hand.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { ApiClient } from "./generated/client.js";
|
|
2
|
+
import { type Sleep } from "./transport.js";
|
|
3
|
+
import { Artifact, ArtifactsResource, DeploymentsResource, type ArtifactRef, type DeployOptions } from "./resources/artifacts.js";
|
|
4
|
+
import { DatasetsResource, ImportsResource } from "./resources/datasets.js";
|
|
5
|
+
import { EvalsResource } from "./resources/evals.js";
|
|
6
|
+
import { KeysResource, ModelsResource, UsageResource } from "./resources/misc.js";
|
|
7
|
+
import { CheckpointsResource, RunsResource } from "./resources/runs.js";
|
|
8
|
+
import { SecretsResource, SourcesResource } from "./resources/sources.js";
|
|
9
|
+
import type { Deployment } from "./generated/models.js";
|
|
10
|
+
export interface GradOptions {
|
|
11
|
+
/** API key (default: the selected profile, GRADIATED_API_KEY, then the default profile). `""` talks to a server without authentication. */
|
|
12
|
+
apiKey?: string | undefined;
|
|
13
|
+
/** API root (default: the selected profile, GRADIATED_BASE_URL, the default profile, then https://api.gradiated.com). A trailing /v1 is dropped. */
|
|
14
|
+
baseURL?: string | undefined;
|
|
15
|
+
/** Config-file profile (default: GRADIATED_PROFILE or "default"). */
|
|
16
|
+
profile?: string | undefined;
|
|
17
|
+
/** Config file path (default: $XDG_CONFIG_HOME/gradiated/config.json or ~/.config/gradiated/config.json). */
|
|
18
|
+
configPath?: string | undefined;
|
|
19
|
+
/** Per-attempt request timeout until response headers (and JSON bodies) arrive; default 60 s. */
|
|
20
|
+
timeoutMs?: number | undefined;
|
|
21
|
+
/** Retries for transient failures (default 2). */
|
|
22
|
+
maxRetries?: number | undefined;
|
|
23
|
+
/** Custom fetch (tests, proxies). */
|
|
24
|
+
fetch?: typeof fetch | undefined;
|
|
25
|
+
defaultHeaders?: Record<string, string> | undefined;
|
|
26
|
+
userAgent?: string | undefined;
|
|
27
|
+
/** Test hooks: the clock used for retry backoff and polling. */
|
|
28
|
+
sleep?: Sleep | undefined;
|
|
29
|
+
now?: (() => number) | undefined;
|
|
30
|
+
random?: (() => number) | undefined;
|
|
31
|
+
}
|
|
32
|
+
export interface ResolvedConfig {
|
|
33
|
+
baseURL: string;
|
|
34
|
+
apiKey: string | undefined;
|
|
35
|
+
apiKeySource: "option" | "env" | "config" | "none";
|
|
36
|
+
/** Set when no key is configured for a non-loopback server: every request fails with it. */
|
|
37
|
+
missingKey?: string | undefined;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The Gradiated training and serving client.
|
|
41
|
+
*
|
|
42
|
+
* ```ts
|
|
43
|
+
* const grad = new Grad(); // GRADIATED_API_KEY, GRADIATED_BASE_URL, or `grad login`
|
|
44
|
+
* const run = await grad.runs.create({ dataset, name: "support-router", recipe: recipes.router() }).wait();
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
export declare class Grad {
|
|
48
|
+
#private;
|
|
49
|
+
/** Low-level typed client: one method per OpenAPI operation (wire-exact, camelCase keys). */
|
|
50
|
+
readonly api: ApiClient;
|
|
51
|
+
readonly models: ModelsResource;
|
|
52
|
+
readonly datasets: DatasetsResource;
|
|
53
|
+
readonly imports: ImportsResource;
|
|
54
|
+
readonly runs: RunsResource;
|
|
55
|
+
readonly checkpoints: CheckpointsResource;
|
|
56
|
+
readonly artifacts: ArtifactsResource;
|
|
57
|
+
readonly deployments: DeploymentsResource;
|
|
58
|
+
readonly evals: EvalsResource;
|
|
59
|
+
readonly keys: KeysResource;
|
|
60
|
+
readonly secrets: SecretsResource;
|
|
61
|
+
readonly sources: SourcesResource;
|
|
62
|
+
readonly usage: UsageResource;
|
|
63
|
+
constructor(options?: GradOptions);
|
|
64
|
+
/** The base URL and key source this client resolved (the key itself is never returned). */
|
|
65
|
+
config(): Promise<{
|
|
66
|
+
baseURL: string;
|
|
67
|
+
apiKeySource: ResolvedConfig["apiKeySource"];
|
|
68
|
+
}>;
|
|
69
|
+
/** Deploys an artifact (same as `grad.deployments.create`). */
|
|
70
|
+
deploy(artifact: ArtifactRef | Artifact, options?: DeployOptions): Promise<Deployment>;
|
|
71
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { ApiClient } from "./generated/client.js";
|
|
2
|
+
import { readEnv, Transport, } from "./transport.js";
|
|
3
|
+
import { DEFAULT_BASE_URL, defaultConfigPath, isLoopback, loadProfile, missingKeyMessage, normalizeBaseURL, validateBaseURL } from "./config.js";
|
|
4
|
+
import { GradUsageError } from "./errors.js";
|
|
5
|
+
import { defaultPollContext } from "./polling.js";
|
|
6
|
+
import { ArtifactsResource, deployArtifact, DeploymentsResource } from "./resources/artifacts.js";
|
|
7
|
+
import { DatasetsResource, ImportsResource } from "./resources/datasets.js";
|
|
8
|
+
import { EvalsResource } from "./resources/evals.js";
|
|
9
|
+
import { KeysResource, ModelsResource, UsageResource } from "./resources/misc.js";
|
|
10
|
+
import { CheckpointsResource, RunsResource } from "./resources/runs.js";
|
|
11
|
+
import { SecretsResource, SourcesResource } from "./resources/sources.js";
|
|
12
|
+
const OPTION_KEYS = new Set([
|
|
13
|
+
"apiKey", "baseURL", "profile", "configPath", "timeoutMs", "maxRetries", "fetch",
|
|
14
|
+
"defaultHeaders", "userAgent", "sleep", "now", "random",
|
|
15
|
+
]);
|
|
16
|
+
/** Throws on an option the client doesn't know (`baseUrl` would otherwise be silently ignored). */
|
|
17
|
+
const checkOptions = (options) => {
|
|
18
|
+
for (const key of Object.keys(options)) {
|
|
19
|
+
if (OPTION_KEYS.has(key))
|
|
20
|
+
continue;
|
|
21
|
+
const near = [...OPTION_KEYS].find((k) => k.toLowerCase() === key.toLowerCase());
|
|
22
|
+
throw new GradUsageError(`Unknown Grad option '${key}'${near ? `; did you mean '${near}'?` : ""} (options: ${[...OPTION_KEYS].join(", ")}).`, "unknown_option");
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Resolves configuration once, with the precedence every SDK and the CLI share:
|
|
27
|
+
* options, then the selected profile (`profile` or GRADIATED_PROFILE), then
|
|
28
|
+
* GRADIATED_API_KEY / GRADIATED_BASE_URL, then the `default` profile of the
|
|
29
|
+
* `grad login` config file, then https://api.gradiated.com. A key saved in a
|
|
30
|
+
* profile is only sent to that profile's own base URL.
|
|
31
|
+
*/
|
|
32
|
+
const resolveConfig = async (options) => {
|
|
33
|
+
const explicit = options.profile ?? readEnv("GRADIATED_PROFILE");
|
|
34
|
+
const name = explicit ?? "default";
|
|
35
|
+
const envURL = readEnv("GRADIATED_BASE_URL");
|
|
36
|
+
const envKey = readEnv("GRADIATED_API_KEY");
|
|
37
|
+
const covered = (options.baseURL ?? envURL) !== undefined && (options.apiKey ?? envKey) !== undefined;
|
|
38
|
+
const path = options.configPath ?? defaultConfigPath();
|
|
39
|
+
const profile = covered && explicit === undefined ? undefined : await loadProfile(path, name);
|
|
40
|
+
if (explicit !== undefined && profile === undefined) {
|
|
41
|
+
throw new GradUsageError(`Profile '${name}' not found in ${path ?? "the grad config file"}; create it with \`grad login --profile ${name}\`.`, "profile_not_found");
|
|
42
|
+
}
|
|
43
|
+
const raw = options.baseURL ?? (explicit !== undefined ? profile?.baseURL : undefined) ?? envURL ?? profile?.baseURL ?? DEFAULT_BASE_URL;
|
|
44
|
+
const baseURL = normalizeBaseURL(raw);
|
|
45
|
+
// A saved key belongs to its profile's server: never send it anywhere else.
|
|
46
|
+
const owner = profile?.baseURL !== undefined ? normalizeBaseURL(profile.baseURL, false) : DEFAULT_BASE_URL;
|
|
47
|
+
const fileKey = profile?.apiKey !== undefined && owner === baseURL ? profile.apiKey : undefined;
|
|
48
|
+
let apiKey;
|
|
49
|
+
let apiKeySource = "none";
|
|
50
|
+
if (options.apiKey !== undefined)
|
|
51
|
+
[apiKey, apiKeySource] = [options.apiKey, "option"];
|
|
52
|
+
else if (explicit !== undefined && fileKey !== undefined)
|
|
53
|
+
[apiKey, apiKeySource] = [fileKey, "config"];
|
|
54
|
+
else if (envKey !== undefined)
|
|
55
|
+
[apiKey, apiKeySource] = [envKey, "env"];
|
|
56
|
+
else if (fileKey !== undefined)
|
|
57
|
+
[apiKey, apiKeySource] = [fileKey, "config"];
|
|
58
|
+
let missingKey;
|
|
59
|
+
if (apiKey === undefined && !isLoopback(baseURL)) {
|
|
60
|
+
const note = profile?.apiKey !== undefined && fileKey === undefined
|
|
61
|
+
? ` (the key saved in profile '${name}' belongs to ${owner}, so it was not sent)`
|
|
62
|
+
: "";
|
|
63
|
+
missingKey = missingKeyMessage(baseURL) + note;
|
|
64
|
+
}
|
|
65
|
+
return { baseURL, apiKey: apiKey === "" ? undefined : apiKey, apiKeySource, missingKey };
|
|
66
|
+
};
|
|
67
|
+
/** Builds the real transport on first use, so configuration can come from a file without blocking the constructor. */
|
|
68
|
+
class LazyTransport {
|
|
69
|
+
options;
|
|
70
|
+
pending;
|
|
71
|
+
constructor(options) {
|
|
72
|
+
this.options = options;
|
|
73
|
+
}
|
|
74
|
+
resolve() {
|
|
75
|
+
this.pending ??= resolveConfig(this.options).then((config) => ({
|
|
76
|
+
config,
|
|
77
|
+
transport: new Transport({
|
|
78
|
+
baseURL: config.baseURL,
|
|
79
|
+
apiKey: config.apiKey,
|
|
80
|
+
timeoutMs: this.options.timeoutMs,
|
|
81
|
+
maxRetries: this.options.maxRetries,
|
|
82
|
+
fetch: this.options.fetch,
|
|
83
|
+
defaultHeaders: this.options.defaultHeaders,
|
|
84
|
+
userAgent: this.options.userAgent,
|
|
85
|
+
sleep: this.options.sleep,
|
|
86
|
+
random: this.options.random,
|
|
87
|
+
}),
|
|
88
|
+
}));
|
|
89
|
+
return this.pending;
|
|
90
|
+
}
|
|
91
|
+
/** The transport for an API request; fails before sending when no key is configured for a remote server. */
|
|
92
|
+
async ready() {
|
|
93
|
+
const { transport, config } = await this.resolve();
|
|
94
|
+
if (config.missingKey !== undefined)
|
|
95
|
+
throw new GradUsageError(config.missingKey, "missing_api_key");
|
|
96
|
+
return transport;
|
|
97
|
+
}
|
|
98
|
+
async json(spec, options) {
|
|
99
|
+
return (await this.ready()).json(spec, options);
|
|
100
|
+
}
|
|
101
|
+
async raw(spec, options) {
|
|
102
|
+
return (await this.ready()).raw(spec, options);
|
|
103
|
+
}
|
|
104
|
+
async *sse(spec, options) {
|
|
105
|
+
yield* (await this.ready()).sse(spec, options);
|
|
106
|
+
}
|
|
107
|
+
/** PUTs to an upload URL without the API key (presigned S3 or the server's signed blob route). */
|
|
108
|
+
async upload(url, headers, body, options) {
|
|
109
|
+
const { config } = await this.resolve();
|
|
110
|
+
const target = new URL(url, `${config.baseURL.replace(/\/+$/, "")}/`);
|
|
111
|
+
const uploader = new Transport({
|
|
112
|
+
baseURL: target.origin,
|
|
113
|
+
apiKey: undefined,
|
|
114
|
+
timeoutMs: this.options.timeoutMs,
|
|
115
|
+
maxRetries: this.options.maxRetries,
|
|
116
|
+
fetch: this.options.fetch,
|
|
117
|
+
userAgent: this.options.userAgent,
|
|
118
|
+
sleep: this.options.sleep,
|
|
119
|
+
random: this.options.random,
|
|
120
|
+
});
|
|
121
|
+
return uploader.raw({ method: "PUT", path: `${target.pathname}${target.search}`, body, headers: Object.entries(headers), accept: "*/*" }, options);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* The Gradiated training and serving client.
|
|
126
|
+
*
|
|
127
|
+
* ```ts
|
|
128
|
+
* const grad = new Grad(); // GRADIATED_API_KEY, GRADIATED_BASE_URL, or `grad login`
|
|
129
|
+
* const run = await grad.runs.create({ dataset, name: "support-router", recipe: recipes.router() }).wait();
|
|
130
|
+
* ```
|
|
131
|
+
*/
|
|
132
|
+
export class Grad {
|
|
133
|
+
/** Low-level typed client: one method per OpenAPI operation (wire-exact, camelCase keys). */
|
|
134
|
+
api;
|
|
135
|
+
models;
|
|
136
|
+
datasets;
|
|
137
|
+
imports;
|
|
138
|
+
runs;
|
|
139
|
+
checkpoints;
|
|
140
|
+
artifacts;
|
|
141
|
+
deployments;
|
|
142
|
+
evals;
|
|
143
|
+
keys;
|
|
144
|
+
secrets;
|
|
145
|
+
sources;
|
|
146
|
+
usage;
|
|
147
|
+
#transport;
|
|
148
|
+
#core;
|
|
149
|
+
constructor(options = {}) {
|
|
150
|
+
checkOptions(options);
|
|
151
|
+
if (options.baseURL !== undefined)
|
|
152
|
+
validateBaseURL(options.baseURL);
|
|
153
|
+
this.#transport = new LazyTransport(options);
|
|
154
|
+
this.api = new ApiClient(this.#transport);
|
|
155
|
+
const poll = {
|
|
156
|
+
sleep: options.sleep ?? defaultPollContext.sleep,
|
|
157
|
+
now: options.now ?? defaultPollContext.now,
|
|
158
|
+
};
|
|
159
|
+
this.#core = {
|
|
160
|
+
api: this.api,
|
|
161
|
+
transport: this.#transport,
|
|
162
|
+
poll,
|
|
163
|
+
upload: (url, headers, body, request) => this.#transport.upload(url, headers, body, request),
|
|
164
|
+
baseURL: async () => (await this.#transport.resolve()).config.baseURL,
|
|
165
|
+
};
|
|
166
|
+
this.models = new ModelsResource(this.#core);
|
|
167
|
+
this.datasets = new DatasetsResource(this.#core);
|
|
168
|
+
this.imports = new ImportsResource(this.#core);
|
|
169
|
+
this.runs = new RunsResource(this.#core);
|
|
170
|
+
this.checkpoints = new CheckpointsResource(this.#core);
|
|
171
|
+
this.artifacts = new ArtifactsResource(this.#core);
|
|
172
|
+
this.deployments = new DeploymentsResource(this.#core);
|
|
173
|
+
this.evals = new EvalsResource(this.#core);
|
|
174
|
+
this.keys = new KeysResource(this.#core);
|
|
175
|
+
this.secrets = new SecretsResource(this.#core);
|
|
176
|
+
this.sources = new SourcesResource(this.#core);
|
|
177
|
+
this.usage = new UsageResource(this.#core);
|
|
178
|
+
}
|
|
179
|
+
/** The base URL and key source this client resolved (the key itself is never returned). */
|
|
180
|
+
async config() {
|
|
181
|
+
const { config } = await this.#transport.resolve();
|
|
182
|
+
return { baseURL: config.baseURL, apiKeySource: config.apiKeySource };
|
|
183
|
+
}
|
|
184
|
+
/** Deploys an artifact (same as `grad.deployments.create`). */
|
|
185
|
+
deploy(artifact, options) {
|
|
186
|
+
return deployArtifact(this.#core, artifact, options);
|
|
187
|
+
}
|
|
188
|
+
}
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export declare const DEFAULT_BASE_URL = "https://api.gradiated.com";
|
|
2
|
+
export interface ProfileConfig {
|
|
3
|
+
baseURL?: string | undefined;
|
|
4
|
+
apiKey?: string | undefined;
|
|
5
|
+
}
|
|
6
|
+
/** `$XDG_CONFIG_HOME/gradiated/config.json`, else `~/.config/gradiated/config.json` (written by `grad login`). */
|
|
7
|
+
export declare const defaultConfigPath: () => string | undefined;
|
|
8
|
+
/**
|
|
9
|
+
* Reads one profile from the CLI config file. Missing file -> undefined; a
|
|
10
|
+
* malformed file is an error (so a typo never silently drops credentials).
|
|
11
|
+
* Node only: in a browser there is no config file.
|
|
12
|
+
*/
|
|
13
|
+
export declare const loadProfile: (path: string | undefined, profile: string) => Promise<ProfileConfig | undefined>;
|
|
14
|
+
/** Fails fast on a base URL that can never work (no scheme, ftp://, ...). */
|
|
15
|
+
export declare const validateBaseURL: (baseURL: string) => void;
|
|
16
|
+
/** The error every SDK and the CLI give when no API key is configured for a remote server. */
|
|
17
|
+
export declare const missingKeyMessage: (baseURL: string) => string;
|
|
18
|
+
/** True when the URL points at this machine (local stacks often run without auth). */
|
|
19
|
+
export declare const isLoopback: (baseURL: string) => boolean;
|
|
20
|
+
/** Strips trailing slashes and a trailing `/v1` (the SDK adds it), warning once per URL. */
|
|
21
|
+
export declare const normalizeBaseURL: (baseURL: string, warn?: boolean) => string;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { GradError, readEnv } from "./transport.js";
|
|
2
|
+
import { GradUsageError } from "./errors.js";
|
|
3
|
+
export const DEFAULT_BASE_URL = "https://api.gradiated.com";
|
|
4
|
+
const isNode = () => typeof globalThis.process?.versions?.node === "string";
|
|
5
|
+
/** `$XDG_CONFIG_HOME/gradiated/config.json`, else `~/.config/gradiated/config.json` (written by `grad login`). */
|
|
6
|
+
export const defaultConfigPath = () => {
|
|
7
|
+
const xdg = readEnv("XDG_CONFIG_HOME");
|
|
8
|
+
if (xdg)
|
|
9
|
+
return `${xdg.replace(/\/+$/, "")}/gradiated/config.json`;
|
|
10
|
+
const home = readEnv("HOME") ?? readEnv("USERPROFILE");
|
|
11
|
+
return home ? `${home.replace(/[\\/]+$/, "")}/.config/gradiated/config.json` : undefined;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Reads one profile from the CLI config file. Missing file -> undefined; a
|
|
15
|
+
* malformed file is an error (so a typo never silently drops credentials).
|
|
16
|
+
* Node only: in a browser there is no config file.
|
|
17
|
+
*/
|
|
18
|
+
export const loadProfile = async (path, profile) => {
|
|
19
|
+
if (!path || !isNode())
|
|
20
|
+
return undefined;
|
|
21
|
+
const fs = await import("node:fs/promises");
|
|
22
|
+
let text;
|
|
23
|
+
try {
|
|
24
|
+
text = await fs.readFile(path, "utf8");
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
if (error.code === "ENOENT")
|
|
28
|
+
return undefined;
|
|
29
|
+
throw new GradUsageError(`Could not read ${path}: ${error.message}`, "config_unreadable");
|
|
30
|
+
}
|
|
31
|
+
let parsed;
|
|
32
|
+
try {
|
|
33
|
+
parsed = JSON.parse(text);
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
throw new GradUsageError(`${path} is not valid JSON; fix it or run \`grad login\` again.`, "config_invalid");
|
|
37
|
+
}
|
|
38
|
+
const profiles = parsed?.profiles;
|
|
39
|
+
const entry = profiles?.[profile];
|
|
40
|
+
if (entry === undefined)
|
|
41
|
+
return undefined;
|
|
42
|
+
if (typeof entry !== "object" || entry === null) {
|
|
43
|
+
throw new GradUsageError(`Profile '${profile}' in ${path} must be an object.`, "config_invalid");
|
|
44
|
+
}
|
|
45
|
+
const { base_url: baseURL, api_key: apiKey } = entry;
|
|
46
|
+
return {
|
|
47
|
+
...(typeof baseURL === "string" && baseURL !== "" ? { baseURL } : {}),
|
|
48
|
+
...(typeof apiKey === "string" && apiKey !== "" ? { apiKey } : {}),
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
/** Fails fast on a base URL that can never work (no scheme, ftp://, ...). */
|
|
52
|
+
export const validateBaseURL = (baseURL) => {
|
|
53
|
+
let parsed;
|
|
54
|
+
try {
|
|
55
|
+
parsed = new URL(baseURL);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
parsed = undefined;
|
|
59
|
+
}
|
|
60
|
+
if (!parsed || (parsed.protocol !== "http:" && parsed.protocol !== "https:")) {
|
|
61
|
+
throw new GradError(`Invalid base URL '${baseURL}': it must be an absolute http(s) URL such as https://api.gradiated.com.`, {
|
|
62
|
+
code: "invalid_base_url",
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
/** The error every SDK and the CLI give when no API key is configured for a remote server. */
|
|
67
|
+
export const missingKeyMessage = (baseURL) => `No API key for ${baseURL}: run \`grad login\`, set GRADIATED_API_KEY, or export GRADIATED_PROFILE=local to use a \`grad local up\` stack.`;
|
|
68
|
+
/** True when the URL points at this machine (local stacks often run without auth). */
|
|
69
|
+
export const isLoopback = (baseURL) => {
|
|
70
|
+
let host;
|
|
71
|
+
try {
|
|
72
|
+
host = new URL(baseURL).hostname.replace(/^\[|\]$/g, "");
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
return host === "localhost" || host.endsWith(".localhost") || host === "::1" || /^127\.\d+\.\d+\.\d+$/.test(host);
|
|
78
|
+
};
|
|
79
|
+
const warned = new Set();
|
|
80
|
+
/** Strips trailing slashes and a trailing `/v1` (the SDK adds it), warning once per URL. */
|
|
81
|
+
export const normalizeBaseURL = (baseURL, warn = true) => {
|
|
82
|
+
const trimmed = baseURL.trim().replace(/\/+$/, "");
|
|
83
|
+
if (!trimmed.endsWith("/v1"))
|
|
84
|
+
return trimmed;
|
|
85
|
+
if (warn && !warned.has(trimmed)) {
|
|
86
|
+
warned.add(trimmed);
|
|
87
|
+
console.warn(`grad: base URL '${trimmed}' ends in /v1; the SDK adds /v1 itself, so it was dropped.`);
|
|
88
|
+
}
|
|
89
|
+
return trimmed.slice(0, -3);
|
|
90
|
+
};
|
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ApiClient } from "./generated/client.js";
|
|
2
|
+
import type { RawResponse, RequestOptions, TransportLike } from "./transport.js";
|
|
3
|
+
import type { PollContext } from "./polling.js";
|
|
4
|
+
/** What every resource needs: the typed API, polling clock, and raw uploads. */
|
|
5
|
+
export interface Core {
|
|
6
|
+
api: ApiClient;
|
|
7
|
+
transport: TransportLike;
|
|
8
|
+
poll: PollContext;
|
|
9
|
+
/** PUTs a replayable body to an upload ticket URL (relative URLs resolve against the API). Never sends the API key. */
|
|
10
|
+
upload: (url: string, headers: Record<string, string>, body: Blob | Uint8Array | string, options?: RequestOptions) => Promise<RawResponse>;
|
|
11
|
+
baseURL: () => Promise<string>;
|
|
12
|
+
}
|
|
13
|
+
export declare const isNodeRuntime: () => boolean;
|
package/dist/core.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const isNodeRuntime = () => typeof globalThis.process?.versions?.node === "string";
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { GradError } from "./transport.js";
|
|
2
|
+
import type { EvalRun, ImportJob, Run } from "./generated/models.js";
|
|
3
|
+
export { APIConnectionError, APIError, APITimeoutError, APIUserAbortError, AuthenticationError, BadRequestError, ConflictError, DeployUnavailableError, GradError, InferenceUnavailableError, NotFoundError, PermissionDeniedError, RateLimitError, RedirectError, ResponseDecodeError, ServerError, ValidationError, type FieldError, } from "./transport.js";
|
|
4
|
+
/** A run ended `failed`, `cancelled`, `stopped_budget` or `stopped_balance`; `run` holds its final state. */
|
|
5
|
+
export declare class RunFailedError extends GradError {
|
|
6
|
+
readonly run: Run;
|
|
7
|
+
constructor(run: Run);
|
|
8
|
+
}
|
|
9
|
+
/** An eval ended `failed` or `cancelled`. */
|
|
10
|
+
export declare class EvalFailedError extends GradError {
|
|
11
|
+
readonly eval: EvalRun;
|
|
12
|
+
constructor(evalRun: EvalRun);
|
|
13
|
+
}
|
|
14
|
+
/** A dataset import ended `failed`. */
|
|
15
|
+
export declare class ImportFailedError extends GradError {
|
|
16
|
+
readonly job: ImportJob;
|
|
17
|
+
constructor(job: ImportJob);
|
|
18
|
+
}
|
|
19
|
+
/** `wait()` gave up after its `timeoutMs`; the resource keeps running server-side. */
|
|
20
|
+
export declare class WaitTimeoutError extends GradError {
|
|
21
|
+
constructor(what: string, timeoutMs: number);
|
|
22
|
+
}
|
|
23
|
+
/** A downloaded artifact's SHA-256 did not match `X-Artifact-Sha256`; nothing was written. */
|
|
24
|
+
export declare class ChecksumMismatchError extends GradError {
|
|
25
|
+
readonly expected: string;
|
|
26
|
+
readonly actual: string;
|
|
27
|
+
constructor(reference: string, expected: string, actual: string);
|
|
28
|
+
}
|
|
29
|
+
/** The server returned a cursor it already returned in this listing; following it would never end. */
|
|
30
|
+
export declare class PaginationLoopError extends GradError {
|
|
31
|
+
readonly cursor: string;
|
|
32
|
+
constructor(cursor: string);
|
|
33
|
+
}
|
|
34
|
+
/** The SDK was used in a way it cannot support (bad options, Node-only feature in a browser, ...). */
|
|
35
|
+
export declare class GradUsageError extends GradError {
|
|
36
|
+
constructor(message: string, code?: string);
|
|
37
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { GradError } from "./transport.js";
|
|
2
|
+
export { APIConnectionError, APIError, APITimeoutError, APIUserAbortError, AuthenticationError, BadRequestError, ConflictError, DeployUnavailableError, GradError, InferenceUnavailableError, NotFoundError, PermissionDeniedError, RateLimitError, RedirectError, ResponseDecodeError, ServerError, ValidationError, } from "./transport.js";
|
|
3
|
+
/** A run ended `failed`, `cancelled`, `stopped_budget` or `stopped_balance`; `run` holds its final state. */
|
|
4
|
+
export class RunFailedError extends GradError {
|
|
5
|
+
run;
|
|
6
|
+
constructor(run) {
|
|
7
|
+
const reason = run.error ? `: ${run.error}` : "";
|
|
8
|
+
const hint = run.status === "stopped_budget"
|
|
9
|
+
? " Raise the cap and continue with grad.runs.resume(id, { maxCostUsd })."
|
|
10
|
+
: run.status === "stopped_balance"
|
|
11
|
+
? " Top up the workspace balance, then continue with grad.runs.resume(id)."
|
|
12
|
+
: "";
|
|
13
|
+
super(`Run ${run.id} (${run.name}) ended ${run.status}${reason}.${hint}`, {
|
|
14
|
+
code: `run_${run.status}`,
|
|
15
|
+
});
|
|
16
|
+
this.run = run;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/** An eval ended `failed` or `cancelled`. */
|
|
20
|
+
export class EvalFailedError extends GradError {
|
|
21
|
+
eval;
|
|
22
|
+
constructor(evalRun) {
|
|
23
|
+
super(`Eval ${evalRun.id} (${evalRun.name}) ended ${evalRun.status}${evalRun.error ? `: ${evalRun.error}` : ""}.`, { code: `eval_${evalRun.status}` });
|
|
24
|
+
this.eval = evalRun;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** A dataset import ended `failed`. */
|
|
28
|
+
export class ImportFailedError extends GradError {
|
|
29
|
+
job;
|
|
30
|
+
constructor(job) {
|
|
31
|
+
super(`Import ${job.id} into dataset '${job.dataset}' failed${job.error ? `: ${job.error}` : ""}.`, { code: "import_failed" });
|
|
32
|
+
this.job = job;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** `wait()` gave up after its `timeoutMs`; the resource keeps running server-side. */
|
|
36
|
+
export class WaitTimeoutError extends GradError {
|
|
37
|
+
constructor(what, timeoutMs) {
|
|
38
|
+
super(`Timed out after ${timeoutMs} ms waiting for ${what}; it keeps running on the server.`, {
|
|
39
|
+
code: "wait_timeout",
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** A downloaded artifact's SHA-256 did not match `X-Artifact-Sha256`; nothing was written. */
|
|
44
|
+
export class ChecksumMismatchError extends GradError {
|
|
45
|
+
expected;
|
|
46
|
+
actual;
|
|
47
|
+
constructor(reference, expected, actual) {
|
|
48
|
+
super(`Artifact ${reference} failed SHA-256 verification: expected ${expected}, got ${actual}. The partial file was removed.`, {
|
|
49
|
+
code: "checksum_mismatch",
|
|
50
|
+
});
|
|
51
|
+
this.expected = expected;
|
|
52
|
+
this.actual = actual;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** The server returned a cursor it already returned in this listing; following it would never end. */
|
|
56
|
+
export class PaginationLoopError extends GradError {
|
|
57
|
+
cursor;
|
|
58
|
+
constructor(cursor) {
|
|
59
|
+
super(`Pagination loop: the server repeated cursor '${cursor}'; stopping instead of fetching forever.`, {
|
|
60
|
+
code: "pagination_loop",
|
|
61
|
+
});
|
|
62
|
+
this.cursor = cursor;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/** The SDK was used in a way it cannot support (bad options, Node-only feature in a browser, ...). */
|
|
66
|
+
export class GradUsageError extends GradError {
|
|
67
|
+
constructor(message, code = "usage_error") {
|
|
68
|
+
super(message, { code });
|
|
69
|
+
}
|
|
70
|
+
}
|