@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.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +83 -2
  3. package/dist/client.d.ts +71 -0
  4. package/dist/client.js +188 -0
  5. package/dist/config.d.ts +21 -0
  6. package/dist/config.js +90 -0
  7. package/dist/core.d.ts +13 -0
  8. package/dist/core.js +1 -0
  9. package/dist/errors.d.ts +37 -0
  10. package/dist/errors.js +70 -0
  11. package/dist/generated/client.d.ts +532 -0
  12. package/dist/generated/client.js +596 -0
  13. package/dist/generated/index.d.ts +2 -0
  14. package/dist/generated/index.js +3 -0
  15. package/dist/generated/models.d.ts +998 -0
  16. package/dist/generated/models.js +9 -0
  17. package/dist/index.d.ts +19 -0
  18. package/dist/index.js +16 -0
  19. package/dist/node/files.d.ts +26 -0
  20. package/dist/node/files.js +130 -0
  21. package/dist/pagination.d.ts +39 -0
  22. package/dist/pagination.js +73 -0
  23. package/dist/pending.d.ts +14 -0
  24. package/dist/pending.js +20 -0
  25. package/dist/polling.d.ts +25 -0
  26. package/dist/polling.js +63 -0
  27. package/dist/recipes.d.ts +220 -0
  28. package/dist/recipes.js +255 -0
  29. package/dist/resources/artifacts.d.ts +82 -0
  30. package/dist/resources/artifacts.js +122 -0
  31. package/dist/resources/datasets.d.ts +178 -0
  32. package/dist/resources/datasets.js +318 -0
  33. package/dist/resources/evals.d.ts +110 -0
  34. package/dist/resources/evals.js +258 -0
  35. package/dist/resources/misc.d.ts +31 -0
  36. package/dist/resources/misc.js +45 -0
  37. package/dist/resources/runs.d.ts +119 -0
  38. package/dist/resources/runs.js +245 -0
  39. package/dist/resources/sources.d.ts +118 -0
  40. package/dist/resources/sources.js +156 -0
  41. package/dist/rubrics.d.ts +87 -0
  42. package/dist/rubrics.js +167 -0
  43. package/dist/trajectory.d.ts +16 -0
  44. package/dist/trajectory.js +13 -0
  45. package/dist/transport.d.ts +229 -0
  46. package/dist/transport.js +678 -0
  47. package/package.json +53 -4
@@ -0,0 +1,255 @@
1
+ import { isNodeRuntime } from "./core.js";
2
+ import { GradUsageError } from "./errors.js";
3
+ import { toRubric } from "./rubrics.js";
4
+ const modelId = (model) => (typeof model === "string" ? model : `${model.name}@${model.version}`);
5
+ export const adapters = {
6
+ /** LoRA adapter (`rank` default 32; `alpha` is fixed at 32 by the server's lr table). */
7
+ lora: (options = {}) => ({
8
+ kind: "lora",
9
+ ...(options.rank !== undefined ? { rank: options.rank } : {}),
10
+ ...(options.alpha !== undefined ? { alpha: options.alpha } : {}),
11
+ ...(options.mergeOnExport !== undefined ? { mergeOnExport: options.mergeOnExport } : {}),
12
+ }),
13
+ /** Trainable prefix KV tokens (cartridges); default 256 tokens. */
14
+ prefixKv: (options = {}) => ({
15
+ kind: "prefix_kv",
16
+ ...(options.numTokens !== undefined ? { numTokens: options.numTokens } : {}),
17
+ }),
18
+ /** Frozen backbone with a trained head (routers, decision models). */
19
+ frozenHead: () => ({ kind: "frozen_head" }),
20
+ };
21
+ const split = (strategy) => (options = {}) => ({
22
+ strategy,
23
+ ...(options.evalFraction !== undefined ? { evalFraction: options.evalFraction } : {}),
24
+ ...(options.seed !== undefined ? { seed: options.seed } : {}),
25
+ });
26
+ /** Train/eval splits (pass as `runs.create({ split })`). Default: by session, 10% held out (15% for routers and decision models). */
27
+ export const splits = {
28
+ bySession: split("by_session"),
29
+ byGroup: split("by_group"),
30
+ random: split("random"),
31
+ };
32
+ /** The loss each recipe trains with; only its parameters are tunable in v0. */
33
+ export const losses = {
34
+ crossEntropy: (options = {}) => ({ kind: "cross_entropy", ...options }),
35
+ dpo: (options = {}) => ({ kind: "dpo", ...options }),
36
+ infoNCE: (options = {}) => ({ kind: "infonce", ...options }),
37
+ topKKLDistill: (options = {}) => ({ kind: "top_k_kl_distill", ...options }),
38
+ };
39
+ /** Distillation rollouts (`recipes.distill({ rollout })`). */
40
+ export const rollouts = {
41
+ /** The student writes each answer (default "auto": sized from your records) and the teacher scores those tokens. */
42
+ onPolicy: (options = {}) => ({
43
+ kind: "on_policy",
44
+ ...(options.maxNewTokens !== undefined && options.maxNewTokens !== "auto" ? { maxNewTokens: options.maxNewTokens } : {}),
45
+ }),
46
+ /** The teacher answers each prompt once through the inference endpoint (a labeling eval) and the student trains on them. */
47
+ offPolicy: (options = {}) => ({
48
+ kind: "off_policy",
49
+ ...(options.maxNewTokens !== undefined ? { maxNewTokens: options.maxNewTokens } : {}),
50
+ }),
51
+ };
52
+ /** AdamW settings (`lr` here is the same as the recipe's `lr`). */
53
+ export const optim = {
54
+ adamW: (options = {}) => ({ kind: "adamw", ...options }),
55
+ };
56
+ /** Embedding pooling. */
57
+ export const pooling = {
58
+ mean: () => ({ kind: "mean" }),
59
+ cls: () => ({ kind: "cls" }),
60
+ };
61
+ /** Text baked into a cartridge. */
62
+ export class Context {
63
+ source;
64
+ constructor(source) {
65
+ this.source = source;
66
+ }
67
+ static fromText(text) {
68
+ return new Context({ text });
69
+ }
70
+ /** Read from disk when the run is submitted (Node only). */
71
+ static fromFile(path) {
72
+ return new Context({ file: path });
73
+ }
74
+ /** The RecipeSpec fields for this context. */
75
+ async toSpec() {
76
+ if ("text" in this.source)
77
+ return { contextText: this.source.text };
78
+ if (!isNodeRuntime())
79
+ throw new GradUsageError("Context.fromFile needs Node.js; use Context.fromText in a browser.", "node_only");
80
+ const { readTextFile } = await import("./node/files.js");
81
+ return { contextText: await readTextFile(this.source.file) };
82
+ }
83
+ }
84
+ const checkpointEval = (item) => {
85
+ if (typeof item === "string")
86
+ return { dataset: item };
87
+ if ("recordCount" in item)
88
+ return { dataset: item.name };
89
+ const { dataset, rubric, ...rest } = item;
90
+ const out = { dataset: typeof dataset === "string" ? dataset : dataset.name, ...rest };
91
+ if (rubric !== undefined) {
92
+ const built = toRubric(rubric);
93
+ if (built.local.size > 0) {
94
+ throw usage(`evals: local scorers (${[...built.local.keys()].join(", ")}) can't run during training; use judges, regexes and validators.`);
95
+ }
96
+ out.rubric = built.wire;
97
+ }
98
+ return out;
99
+ };
100
+ /** Experiment trackers for recipe `loggers`; keys come from workspace secrets. A failing tracker never fails the run. */
101
+ export const loggers = {
102
+ /** Weights & Biases: `secret` names the workspace secret holding the API key. */
103
+ wandb: (options) => ({ kind: "wandb", ...options }),
104
+ /** MLflow: `secret` names a workspace secret with a bearer token, if the server needs one. */
105
+ mlflow: (options) => ({ kind: "mlflow", ...options }),
106
+ };
107
+ const COMMON_KEYS = [
108
+ "model", "adapter", "lr", "lrScale", "optimizer", "batchSize", "epochs", "schedule", "warmup", "trainOn", "thinking",
109
+ "preserveThinking", "reduction", "select", "checkpointTtlDays", "evalEvery", "evals", "loggers",
110
+ ];
111
+ /** A recipe ready to submit; build one with `recipes.*`. */
112
+ export class Recipe {
113
+ kind;
114
+ fields;
115
+ context;
116
+ constructor(kind, fields, context) {
117
+ this.kind = kind;
118
+ this.fields = fields;
119
+ this.context = context;
120
+ }
121
+ /** The wire RecipeSpec (only the fields you set; the server applies documented defaults). */
122
+ async toSpec() {
123
+ const extra = this.context ? await this.context.toSpec() : {};
124
+ return { kind: this.kind, ...this.fields, ...extra };
125
+ }
126
+ }
127
+ const usage = (message) => new GradUsageError(message, "unsupported_recipe_option");
128
+ const common = (options) => {
129
+ const out = {};
130
+ for (const key of COMMON_KEYS)
131
+ if (options[key] !== undefined)
132
+ out[key] = options[key];
133
+ if (options.model !== undefined)
134
+ out.model = modelId(options.model);
135
+ if (options.evalEvery === "auto")
136
+ delete out.evalEvery;
137
+ if (options.evals !== undefined)
138
+ out.evals = options.evals.map(checkpointEval);
139
+ if (options.optimizer !== undefined) {
140
+ const { lr, kind, betas, weightDecay, gradClip } = options.optimizer;
141
+ if (lr !== undefined) {
142
+ if (options.lr !== undefined && options.lr !== lr)
143
+ throw usage(`lr ${String(options.lr)} conflicts with optim.adamW({ lr: ${lr} }).`);
144
+ out.lr = lr;
145
+ }
146
+ const optimizer = { kind, betas: betas ?? [0.9, 0.95], weightDecay: weightDecay ?? 0, gradClip: gradClip ?? 1 };
147
+ out.optimizer = optimizer;
148
+ }
149
+ return out;
150
+ };
151
+ const build = (recipe, options, extra) => {
152
+ const known = new Set([...COMMON_KEYS, ...extra]);
153
+ const unknown = Object.keys(options).filter((k) => !known.has(k));
154
+ if (unknown.length > 0) {
155
+ throw usage(`recipes.${recipe}() does not support ${unknown.map((k) => `'${k}'`).join(", ")}; it would be ignored, so it is rejected.`);
156
+ }
157
+ return common(options);
158
+ };
159
+ /** A loss shorthand: `loss` sets the same field as the recipe's own option, which must agree. */
160
+ const fromLoss = (recipe, field, direct, viaLoss) => {
161
+ if (direct !== undefined && viaLoss !== undefined && direct !== viaLoss)
162
+ throw usage(`recipes.${recipe}(): ${field} conflicts with loss.${field}.`);
163
+ return direct ?? viaLoss;
164
+ };
165
+ const set = (key, value) => value === undefined ? {} : { [key]: value };
166
+ export const recipes = {
167
+ /** Supervised fine-tuning on chat records. */
168
+ sft: (options = {}) => {
169
+ const fields = build("sft", options, ["mergeOnExport", "loss"]);
170
+ const reduction = fromLoss("sft", "reduction", options.reduction, options.loss?.reduction);
171
+ if (options.mergeOnExport !== undefined) {
172
+ const adapter = fields.adapter ?? { kind: "lora" };
173
+ if (adapter.kind !== "lora")
174
+ throw usage("mergeOnExport needs a LoRA adapter.");
175
+ fields.adapter = { ...adapter, mergeOnExport: options.mergeOnExport };
176
+ }
177
+ return new Recipe("sft", { ...fields, ...set("reduction", reduction) });
178
+ },
179
+ /** Direct preference optimization on chosen/rejected pairs (pass `model: sftRun.artifact` to continue an SFT run). */
180
+ dpo: (options = {}) => {
181
+ const fields = build("dpo", options, ["beta", "loss"]);
182
+ return new Recipe("dpo", { ...fields, ...set("beta", fromLoss("dpo", "beta", options.beta, options.loss?.beta)) });
183
+ },
184
+ /** Learned router across candidate models (default backbone qwen/qwen3-0.6b). */
185
+ router: (options = {}) => {
186
+ const fields = build("router", options, ["models", "maxQualityDrop", "rubric", "pricing", "fallback"]);
187
+ let rubric;
188
+ if (typeof options.rubric === "string")
189
+ rubric = options.rubric;
190
+ else if (options.rubric !== undefined) {
191
+ const { wire, local } = toRubric(options.rubric);
192
+ if (local.size > 0)
193
+ throw usage("recipes.router({ rubric }) cannot run local scorer functions (that needs a sandbox, post-v0); use a Judge or validators.");
194
+ if (options.models === undefined)
195
+ throw usage("recipes.router({ rubric: Judge }) replays your prompts against the candidates: pass models.");
196
+ rubric = wire;
197
+ }
198
+ return new Recipe("router", {
199
+ ...fields,
200
+ ...set("models", options.models?.map(modelId)),
201
+ ...set("maxQualityDrop", options.maxQualityDrop),
202
+ ...set("rubric", rubric),
203
+ ...set("pricing", options.pricing),
204
+ ...set("fallback", options.fallback === undefined ? undefined : modelId(options.fallback)),
205
+ });
206
+ },
207
+ /** Decision model (default backbone gradiated/linden-1). */
208
+ decisionModel: (options = {}) => new Recipe("decision", build("decisionModel", options, [])),
209
+ /** Context cartridge: compress a document into trainable prefix KV tokens. */
210
+ cartridge: (options) => {
211
+ const fields = build("cartridge", options, ["context", "numTokens", "teacher", "loss", "maxNewTokens"]);
212
+ if (!(options.context instanceof Context))
213
+ throw new GradUsageError("recipes.cartridge() needs context: Context.fromText/fromFile(...).", "invalid_recipe");
214
+ return new Recipe("cartridge", {
215
+ ...fields,
216
+ ...set("numTokens", options.numTokens),
217
+ ...set("teacher", options.teacher === undefined ? undefined : modelId(options.teacher)),
218
+ ...set("loss", options.loss),
219
+ ...set("maxNewTokens", options.maxNewTokens),
220
+ }, options.context);
221
+ },
222
+ /**
223
+ * Distillation: a LoRA student learns a teacher on your prompts. On-policy (default) the teacher
224
+ * must be a catalog model sharing the student's tokenizer; off-policy it can be an Artifact or any
225
+ * model the inference endpoint serves.
226
+ */
227
+ distill: (options) => {
228
+ const fields = build("distill", options, ["teacher", "rollout", "loss", "context"]);
229
+ if (options.teacher === undefined)
230
+ throw new GradUsageError("recipes.distill() needs teacher: a catalog model or an Artifact.", "invalid_recipe");
231
+ const offPolicy = options.rollout?.kind === "off_policy";
232
+ const expected = offPolicy ? "cross_entropy" : "top_k_kl_distill";
233
+ if (options.loss !== undefined && options.loss.kind !== expected) {
234
+ throw usage(`recipes.distill(): ${offPolicy ? "off" : "on"}-policy distillation trains with loss kind '${expected}', not '${options.loss.kind}'.`);
235
+ }
236
+ if (options.context !== undefined && offPolicy)
237
+ throw usage("recipes.distill(): context is read by the teacher on-policy; drop rollout: rollouts.offPolicy().");
238
+ return new Recipe("distill", { ...fields, teacher: modelId(options.teacher), ...set("rollout", options.rollout), ...set("loss", options.loss) }, options.context);
239
+ },
240
+ /** Reward model: a scalar head trained on chosen/rejected pairs (and, with `rubric`, scored answers). */
241
+ rewardModel: (options = {}) => {
242
+ const fields = build("rewardModel", options, ["rubric"]);
243
+ return new Recipe("reward", { ...fields, ...set("rubric", options.rubric) });
244
+ },
245
+ /** Embedding model (full encoder fine-tune; default baai/bge-small-en-v1.5). */
246
+ embedding: (options = {}) => {
247
+ const fields = build("embedding", options, ["temp", "loss", "pool"]);
248
+ return new Recipe("embedding", {
249
+ ...fields,
250
+ ...set("temp", fromLoss("embedding", "temp", options.temp, options.loss?.temp)),
251
+ ...set("pool", options.pool),
252
+ });
253
+ },
254
+ };
255
+ export const toRecipeSpec = async (recipe) => (recipe instanceof Recipe ? recipe.toSpec() : recipe);
@@ -0,0 +1,82 @@
1
+ import type { Artifact as ArtifactData, Deployment, DeploymentStatus } from "../generated/models.js";
2
+ import { type RawResponse, type RequestOptions, type StreamOptions } from "../transport.js";
3
+ import { type Core } from "../core.js";
4
+ import { Paginator } from "../pagination.js";
5
+ export type ArtifactRef = string | {
6
+ id: string;
7
+ } | {
8
+ name: string;
9
+ version: string;
10
+ };
11
+ /** `name@version` for Artifact objects, the string itself otherwise. */
12
+ export declare const artifactRef: (ref: ArtifactRef) => string;
13
+ export interface DeployOptions extends RequestOptions {
14
+ /** Deployment name (default: the artifact name). */
15
+ name?: string;
16
+ /** Model that serves traffic when a router can't, or after a rollback. */
17
+ fallback?: string;
18
+ /** Share of traffic routed to exploration (routers). */
19
+ exploreRate?: number;
20
+ }
21
+ export interface DownloadOptions extends StreamOptions {
22
+ /** Verify `X-Artifact-Sha256` (default true). Disable only for debugging. */
23
+ verifyChecksum?: boolean;
24
+ }
25
+ export interface ArtifactStream {
26
+ /** The bundle bytes (`.grad.tar.gz`), streamed. */
27
+ body: ReadableStream<Uint8Array>;
28
+ /** Lower-case hex SHA-256 the server declared (undefined when missing or malformed). */
29
+ sha256: string | undefined;
30
+ sizeBytes: number | undefined;
31
+ filename: string | undefined;
32
+ response: RawResponse;
33
+ }
34
+ export declare const deployArtifact: (core: Core, ref: ArtifactRef, options?: DeployOptions) => Promise<Deployment>;
35
+ export declare const openArtifact: (core: Core, ref: string, options?: StreamOptions) => Promise<ArtifactStream>;
36
+ export interface DownloadResult {
37
+ path: string;
38
+ sha256: string;
39
+ sizeBytes: number;
40
+ }
41
+ /** Streams an artifact to disk with SHA-256 verification (Node only). */
42
+ export declare const downloadArtifact: (core: Core, ref: string, dest: string, options?: DownloadOptions) => Promise<DownloadResult>;
43
+ /** An immutable, versioned training output (`name@YYYY-MM-DD-n`). */
44
+ export interface Artifact extends ArtifactData {
45
+ }
46
+ export declare class Artifact {
47
+ #private;
48
+ constructor(core: Core, data: ArtifactData);
49
+ /** `name@version`. */
50
+ get ref(): string;
51
+ /** Points `your-org/<name>` at this version (Cloud; self-hosted servers raise DeployUnavailableError). */
52
+ deploy(options?: DeployOptions): Promise<Deployment>;
53
+ /** Streams the bundle to `dest` (a file, or a directory for the server's file name), verifying SHA-256. */
54
+ download(dest: string, options?: DownloadOptions): Promise<DownloadResult>;
55
+ /** The raw bundle stream plus the declared checksum (browser-safe). */
56
+ stream(options?: StreamOptions): Promise<ArtifactStream>;
57
+ toJSON(): ArtifactData;
58
+ }
59
+ export declare class ArtifactsResource {
60
+ private readonly core;
61
+ constructor(core: Core);
62
+ /** By id, `name@version` or `name@latest`. */
63
+ get(ref: string, options?: RequestOptions): Promise<Artifact>;
64
+ list(options?: {
65
+ name?: string;
66
+ limit?: number;
67
+ } & RequestOptions): Paginator<Artifact>;
68
+ download(ref: ArtifactRef, dest: string, options?: DownloadOptions): Promise<DownloadResult>;
69
+ stream(ref: ArtifactRef, options?: StreamOptions): Promise<ArtifactStream>;
70
+ }
71
+ export declare class DeploymentsResource {
72
+ private readonly core;
73
+ constructor(core: Core);
74
+ /** Deploys an artifact; deploying an earlier version is a rollback. */
75
+ create(artifact: ArtifactRef, options?: DeployOptions): Promise<Deployment>;
76
+ get(name: string, options?: RequestOptions): Promise<DeploymentStatus>;
77
+ list(options?: {
78
+ limit?: number;
79
+ } & RequestOptions): Paginator<Deployment>;
80
+ /** Re-points the deployment at its previous artifact. */
81
+ rollback(name: string, options?: RequestOptions): Promise<Deployment>;
82
+ }
@@ -0,0 +1,122 @@
1
+ import { GradError } from "../transport.js";
2
+ import { isNodeRuntime } from "../core.js";
3
+ import { GradUsageError } from "../errors.js";
4
+ import { Paginator } from "../pagination.js";
5
+ /** `name@version` for Artifact objects, the string itself otherwise. */
6
+ export const artifactRef = (ref) => {
7
+ if (typeof ref === "string")
8
+ return ref;
9
+ if ("version" in ref && "name" in ref)
10
+ return `${ref.name}@${ref.version}`;
11
+ return ref.id;
12
+ };
13
+ const HEX64 = /^[0-9a-f]{64}$/;
14
+ export const deployArtifact = async (core, ref, options = {}) => {
15
+ const { name, fallback, exploreRate, ...request } = options;
16
+ return core.api.deployArtifact({
17
+ artifact: artifactRef(ref),
18
+ ...(name !== undefined ? { name } : {}),
19
+ ...(fallback !== undefined ? { fallback } : {}),
20
+ ...(exploreRate !== undefined ? { exploreRate } : {}),
21
+ }, request);
22
+ };
23
+ export const openArtifact = async (core, ref, options) => {
24
+ const response = await core.api.downloadArtifact(ref, options);
25
+ const declared = response.headers.get("x-artifact-sha256")?.trim().toLowerCase();
26
+ const length = response.headers.get("content-length");
27
+ const disposition = response.headers.get("content-disposition");
28
+ return {
29
+ body: response.body,
30
+ sha256: declared && HEX64.test(declared) ? declared : undefined,
31
+ sizeBytes: length !== null && /^\d+$/.test(length) ? Number(length) : undefined,
32
+ filename: disposition ? /filename="?([^";]+)"?/i.exec(disposition)?.[1] : undefined,
33
+ response,
34
+ };
35
+ };
36
+ /** Streams an artifact to disk with SHA-256 verification (Node only). */
37
+ export const downloadArtifact = async (core, ref, dest, options = {}) => {
38
+ if (!isNodeRuntime()) {
39
+ throw new GradUsageError("artifacts.download writes to disk and needs Node.js; use artifacts.stream() in a browser.", "node_only");
40
+ }
41
+ const { verifyChecksum = true, ...request } = options;
42
+ const { streamToFile } = await import("../node/files.js");
43
+ const opened = await openArtifact(core, ref, request);
44
+ if (verifyChecksum && opened.sha256 === undefined) {
45
+ await opened.response.cancel();
46
+ throw new GradError(`Artifact ${ref} download has no valid X-Artifact-Sha256 header, so it cannot be verified. Pass verifyChecksum: false only if you trust the transport.`, { code: "missing_checksum", requestId: opened.response.requestId });
47
+ }
48
+ return streamToFile(opened.response, dest, ref, verifyChecksum ? opened.sha256 : undefined);
49
+ };
50
+ export class Artifact {
51
+ #core;
52
+ constructor(core, data) {
53
+ this.#core = core;
54
+ Object.assign(this, data);
55
+ }
56
+ /** `name@version`. */
57
+ get ref() {
58
+ return `${this.name}@${this.version}`;
59
+ }
60
+ /** Points `your-org/<name>` at this version (Cloud; self-hosted servers raise DeployUnavailableError). */
61
+ async deploy(options) {
62
+ return deployArtifact(this.#core, this.id, options);
63
+ }
64
+ /** Streams the bundle to `dest` (a file, or a directory for the server's file name), verifying SHA-256. */
65
+ async download(dest, options) {
66
+ return downloadArtifact(this.#core, this.id, dest, options);
67
+ }
68
+ /** The raw bundle stream plus the declared checksum (browser-safe). */
69
+ stream(options) {
70
+ return openArtifact(this.#core, this.id, options);
71
+ }
72
+ toJSON() {
73
+ return { ...this };
74
+ }
75
+ }
76
+ export class ArtifactsResource {
77
+ core;
78
+ constructor(core) {
79
+ this.core = core;
80
+ }
81
+ /** By id, `name@version` or `name@latest`. */
82
+ async get(ref, options) {
83
+ return new Artifact(this.core, await this.core.api.getArtifact(ref, options));
84
+ }
85
+ list(options = {}) {
86
+ const { name, limit, ...request } = options;
87
+ return new Paginator(async (cursor) => {
88
+ const page = await this.core.api.listArtifacts({ ...(name !== undefined ? { name } : {}), ...(limit !== undefined ? { limit } : {}), ...(cursor ? { cursor } : {}) }, request);
89
+ return { data: page.data.map((a) => new Artifact(this.core, a)), nextCursor: page.nextCursor };
90
+ }, request.signal);
91
+ }
92
+ download(ref, dest, options) {
93
+ return downloadArtifact(this.core, artifactRef(ref), dest, options);
94
+ }
95
+ stream(ref, options) {
96
+ return openArtifact(this.core, artifactRef(ref), options);
97
+ }
98
+ }
99
+ export class DeploymentsResource {
100
+ core;
101
+ constructor(core) {
102
+ this.core = core;
103
+ }
104
+ /** Deploys an artifact; deploying an earlier version is a rollback. */
105
+ create(artifact, options) {
106
+ return deployArtifact(this.core, artifact, options);
107
+ }
108
+ get(name, options) {
109
+ return this.core.api.getDeployment(name, options);
110
+ }
111
+ list(options = {}) {
112
+ const { limit, ...request } = options;
113
+ return new Paginator(async (cursor) => {
114
+ const page = await this.core.api.listDeployments({ ...(limit !== undefined ? { limit } : {}), ...(cursor ? { cursor } : {}) }, request);
115
+ return { data: page.data, nextCursor: page.nextCursor };
116
+ }, request.signal);
117
+ }
118
+ /** Re-points the deployment at its previous artifact. */
119
+ rollback(name, options) {
120
+ return this.core.api.rollbackDeployment(name, options);
121
+ }
122
+ }
@@ -0,0 +1,178 @@
1
+ import type { Dataset as DatasetData, FilterDatasetRequest, DatasetRecord, HfColumnMapping, ImportJob as ImportJobData, ImportSource, RenderDatasetRequest, RenderDatasetResponse } from "../generated/models.js";
2
+ import type { RequestOptions } from "../transport.js";
3
+ import { type Core } from "../core.js";
4
+ import { Paginator } from "../pagination.js";
5
+ import { Pending } from "../pending.js";
6
+ import { type WaitOptions } from "../polling.js";
7
+ import { type RubricInput } from "../rubrics.js";
8
+ import { type PendingScoring } from "./evals.js";
9
+ import { type AddSourceOptions, type SecretLike, type Source } from "./sources.js";
10
+ export type DatasetRef = string | {
11
+ name: string;
12
+ };
13
+ export declare const datasetName: (ref: DatasetRef) => string;
14
+ type Connector = NonNullable<ImportJobData["connector"]>;
15
+ export interface ImportFileOptions extends RequestOptions {
16
+ /** Trace format; `auto` detects OpenAI chat, OTel, Langfuse, PostHog, Braintrust, LangSmith and grad.trajectory/1. */
17
+ connector?: Connector;
18
+ format?: "auto" | "jsonl" | "json" | "parquet";
19
+ }
20
+ export interface FromHfOptions extends WaitOptions {
21
+ /** Dataset name to create (default: derived from the repo and split). */
22
+ name?: string;
23
+ split?: string;
24
+ /** HF config / subset name. */
25
+ subset?: string;
26
+ revision?: string;
27
+ limit?: number;
28
+ connector?: Connector;
29
+ /** Column mapping (also accepted at the top level: `prompt: "question"`). */
30
+ columns?: HfColumnMapping;
31
+ messages?: string;
32
+ prompt?: string;
33
+ completion?: string;
34
+ chosen?: string;
35
+ rejected?: string;
36
+ answer?: string;
37
+ query?: string;
38
+ positive?: string;
39
+ /** Workspace secret with a Hugging Face token, for gated or private datasets. */
40
+ secret?: SecretLike;
41
+ }
42
+ export interface PushOptions extends RequestOptions {
43
+ metadata?: Record<string, unknown>;
44
+ /** Records per request (default 1000). */
45
+ batchSize?: number;
46
+ /** Approximate JSON bytes per request (default 8 MiB; the server caps bodies at 32 MiB). */
47
+ maxBatchBytes?: number;
48
+ }
49
+ export interface ScoreOptions extends RequestOptions {
50
+ /** Version to score (default: the current one). */
51
+ version?: number;
52
+ /** Name of the scoring job (default `<dataset>-score`). */
53
+ name?: string;
54
+ limit?: number;
55
+ }
56
+ /** Options of a filter function run locally: the source version and the view name. */
57
+ export interface ViewOptions extends RequestOptions {
58
+ /** Source version (default: the current one). */
59
+ version?: number;
60
+ /** View name (default `<dataset>-f-<hash>`, the same for the same filter). */
61
+ name?: string;
62
+ }
63
+ /** Field filters run on the server; `scores` conditions look like `">=0.8"`. */
64
+ export interface FilterOptions extends ViewOptions, Omit<FilterDatasetRequest, "createdAfter" | "createdBefore" | "version" | "name"> {
65
+ /** On the record `timestamp`: a Date, an ISO timestamp or a UTC date `YYYY-MM-DD`. */
66
+ createdAfter?: string | Date;
67
+ createdBefore?: string | Date;
68
+ }
69
+ export type RecordPredicate = (record: DatasetRecord) => boolean | Promise<boolean>;
70
+ /** An async import job; `wait()` resolves when the records are in the dataset. */
71
+ export interface ImportJob extends ImportJobData {
72
+ }
73
+ export declare class ImportJob {
74
+ #private;
75
+ constructor(core: Core, data: ImportJobData);
76
+ refresh(options?: RequestOptions): Promise<this>;
77
+ /** Polls until `completed` (throws ImportFailedError on `failed`). */
78
+ wait(options?: WaitOptions): Promise<ImportJob>;
79
+ }
80
+ export type PendingImport = Pending<ImportJob, ImportJob, WaitOptions>;
81
+ /** A named, versioned set of records. */
82
+ export interface Dataset extends DatasetData {
83
+ }
84
+ export declare class Dataset {
85
+ #private;
86
+ constructor(core: Core, data: DatasetData);
87
+ refresh(options?: RequestOptions): Promise<this>;
88
+ /** Current record count (refreshes from the server). */
89
+ count(options?: RequestOptions): Promise<number>;
90
+ /** Appends records (or a JSONL file path in Node). */
91
+ push(records: DatasetRecord[] | Iterable<DatasetRecord> | AsyncIterable<DatasetRecord> | string, options?: PushOptions): Promise<this>;
92
+ /** Uploads a JSONL/JSON/Parquet trace file and starts an import (Node only). */
93
+ importFile(path: string, options?: ImportFileOptions): PendingImport;
94
+ /** Imports a Hugging Face dataset into this dataset. */
95
+ importHf(repo: string, options?: Omit<FromHfOptions, "name">): PendingImport;
96
+ /** Records of the current (or a given) version, page by page. */
97
+ records(options?: {
98
+ version?: number;
99
+ limit?: number;
100
+ } & RequestOptions): Paginator<DatasetRecord>;
101
+ /** Connects an observability provider: `dataset.addSource({ provider: sources.langfuse({...}) })`. */
102
+ addSource(options: AddSourceOptions): Promise<Source>;
103
+ /** Shows exactly which tokens train for the first few records. */
104
+ render(options?: RenderDatasetRequest, request?: RequestOptions): Promise<RenderDatasetResponse>;
105
+ /**
106
+ * Scores the records' own answers with judges, validators or local scorers
107
+ * (server-side, billed like an eval); `.wait()` resolves to the dataset whose
108
+ * next version carries the scores. Records with every score are skipped.
109
+ */
110
+ score(rubric: RubricInput, options?: ScoreOptions): PendingScoring;
111
+ /**
112
+ * Saves a filtered view: field filters (`{ scores: { resolved: ">=0.8" } }`)
113
+ * run on the server for free; a function runs here over the streamed records
114
+ * and the matching ids are saved as the view.
115
+ */
116
+ filter(filter: FilterOptions | RecordPredicate, options?: ViewOptions): Promise<Dataset>;
117
+ toJSON(): DatasetData;
118
+ }
119
+ export declare const scoreDataset: (core: Core, name: string, rubric: RubricInput, options?: ScoreOptions) => PendingScoring;
120
+ export declare const filterDataset: (core: Core, name: string, filter: FilterOptions | RecordPredicate, options?: ViewOptions) => Promise<Dataset>;
121
+ export declare const pushRecords: (core: Core, name: string, records: DatasetRecord[] | Iterable<DatasetRecord> | AsyncIterable<DatasetRecord> | string, options?: PushOptions) => Promise<DatasetData>;
122
+ export declare const hfDatasetName: (repo: string, split?: string) => string;
123
+ export type BenchmarkName = Extract<ImportSource, {
124
+ kind: "benchmark";
125
+ }>["benchmark"];
126
+ export interface FromBenchmarkOptions extends WaitOptions {
127
+ /** Import the first N problems (the same ones every time). */
128
+ limit?: number;
129
+ /** Dataset name (default `<benchmark>-<limit>`, or `<benchmark>`). */
130
+ name?: string;
131
+ /** `false` returns once the import is queued (default: wait for it). */
132
+ wait?: boolean;
133
+ }
134
+ export declare class DatasetsResource {
135
+ private readonly core;
136
+ constructor(core: Core);
137
+ /**
138
+ * Imports a built-in benchmark (`gsm8k`, `mmlu`, `mmlu_pro`, `arc_challenge`)
139
+ * from Hugging Face at a pinned revision with fixed prompts; an eval on it
140
+ * without a rubric uses the benchmark's answer check.
141
+ */
142
+ fromBenchmark(benchmark: BenchmarkName, options?: FromBenchmarkOptions): Promise<Dataset>;
143
+ /** Creates an empty dataset (409 ConflictError if the name exists). */
144
+ create(name: string, options?: {
145
+ metadata?: Record<string, unknown>;
146
+ } & RequestOptions): Promise<Dataset>;
147
+ get(name: string, options?: RequestOptions): Promise<Dataset>;
148
+ list(options?: {
149
+ limit?: number;
150
+ } & RequestOptions): Paginator<Dataset>;
151
+ /** Pushes records (or a JSONL path in Node), creating the dataset if needed. Large inputs go in batches. */
152
+ push(name: string, records: DatasetRecord[] | Iterable<DatasetRecord> | AsyncIterable<DatasetRecord> | string, options?: PushOptions): Promise<Dataset>;
153
+ records(name: string, options?: {
154
+ version?: number;
155
+ limit?: number;
156
+ } & RequestOptions): Paginator<DatasetRecord>;
157
+ render(name: string, options?: RenderDatasetRequest, request?: RequestOptions): Promise<RenderDatasetResponse>;
158
+ /** See `Dataset.score`. */
159
+ score(name: DatasetRef, rubric: RubricInput, options?: ScoreOptions): PendingScoring;
160
+ /** See `Dataset.filter`. */
161
+ filter(name: DatasetRef, filter: FilterOptions | RecordPredicate, options?: ViewOptions): Promise<Dataset>;
162
+ importFile(name: DatasetRef, path: string, options?: ImportFileOptions): PendingImport;
163
+ /**
164
+ * Imports a Hugging Face dataset into a new (or existing) dataset and waits
165
+ * for it: `await grad.datasets.fromHf("openai/gsm8k", { subset: "main", prompt: "question", answer: "answer" })`.
166
+ */
167
+ fromHf(repo: string, options?: FromHfOptions): Promise<Dataset>;
168
+ }
169
+ export declare class ImportsResource {
170
+ private readonly core;
171
+ constructor(core: Core);
172
+ get(id: string, options?: RequestOptions): Promise<ImportJob>;
173
+ list(options?: {
174
+ limit?: number;
175
+ } & RequestOptions): Paginator<ImportJob>;
176
+ wait(id: string, options?: WaitOptions): Promise<ImportJob>;
177
+ }
178
+ export {};