@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,318 @@
1
+ import { isNodeRuntime } from "../core.js";
2
+ import { GradUsageError, ImportFailedError } from "../errors.js";
3
+ import { Paginator } from "../pagination.js";
4
+ import { Pending } from "../pending.js";
5
+ import { pollUntil } from "../polling.js";
6
+ import { toRubric } from "../rubrics.js";
7
+ import { DatasetScoring } from "./evals.js";
8
+ import { addSource, secretName } from "./sources.js";
9
+ export const datasetName = (ref) => (typeof ref === "string" ? ref : ref.name);
10
+ const DEFAULT_BATCH = 1000;
11
+ const DEFAULT_BATCH_BYTES = 8 * 1024 * 1024;
12
+ export class ImportJob {
13
+ #core;
14
+ constructor(core, data) {
15
+ this.#core = core;
16
+ Object.assign(this, data);
17
+ }
18
+ async refresh(options) {
19
+ Object.assign(this, await this.#core.api.getImport(this.id, options));
20
+ return this;
21
+ }
22
+ /** Polls until `completed` (throws ImportFailedError on `failed`). */
23
+ async wait(options = {}) {
24
+ const done = await pollUntil(`import ${this.id}`, (signal) => this.#core.api.getImport(this.id, { signal }), (job) => job.status === "completed" || job.status === "failed", options, this.#core.poll);
25
+ Object.assign(this, done);
26
+ if (done.status === "failed")
27
+ throw new ImportFailedError(done);
28
+ return this;
29
+ }
30
+ }
31
+ export class Dataset {
32
+ #core;
33
+ constructor(core, data) {
34
+ this.#core = core;
35
+ Object.assign(this, data);
36
+ }
37
+ async refresh(options) {
38
+ Object.assign(this, await this.#core.api.getDataset(this.name, options));
39
+ return this;
40
+ }
41
+ /** Current record count (refreshes from the server). */
42
+ async count(options) {
43
+ await this.refresh(options);
44
+ return this.recordCount;
45
+ }
46
+ /** Appends records (or a JSONL file path in Node). */
47
+ async push(records, options) {
48
+ Object.assign(this, await pushRecords(this.#core, this.name, records, options));
49
+ return this;
50
+ }
51
+ /** Uploads a JSONL/JSON/Parquet trace file and starts an import (Node only). */
52
+ importFile(path, options = {}) {
53
+ return new Pending(importFile(this.#core, this.name, path, options));
54
+ }
55
+ /** Imports a Hugging Face dataset into this dataset. */
56
+ importHf(repo, options = {}) {
57
+ return new Pending(importHf(this.#core, this.name, repo, options));
58
+ }
59
+ /** Records of the current (or a given) version, page by page. */
60
+ records(options = {}) {
61
+ const { version, limit, ...request } = options;
62
+ return new Paginator(async (cursor) => {
63
+ const page = await this.#core.api.listDatasetRecords(this.name, { ...(version !== undefined ? { version } : {}), ...(limit !== undefined ? { limit } : {}), ...(cursor ? { cursor } : {}) }, request);
64
+ return { data: page.data, nextCursor: page.nextCursor };
65
+ }, request.signal);
66
+ }
67
+ /** Connects an observability provider: `dataset.addSource({ provider: sources.langfuse({...}) })`. */
68
+ addSource(options) {
69
+ return addSource(this.#core, this.name, options);
70
+ }
71
+ /** Shows exactly which tokens train for the first few records. */
72
+ render(options = {}, request) {
73
+ return this.#core.api.renderDataset(this.name, options, request);
74
+ }
75
+ /**
76
+ * Scores the records' own answers with judges, validators or local scorers
77
+ * (server-side, billed like an eval); `.wait()` resolves to the dataset whose
78
+ * next version carries the scores. Records with every score are skipped.
79
+ */
80
+ score(rubric, options = {}) {
81
+ return scoreDataset(this.#core, this.name, rubric, options);
82
+ }
83
+ /**
84
+ * Saves a filtered view: field filters (`{ scores: { resolved: ">=0.8" } }`)
85
+ * run on the server for free; a function runs here over the streamed records
86
+ * and the matching ids are saved as the view.
87
+ */
88
+ filter(filter, options = {}) {
89
+ return filterDataset(this.#core, this.name, filter, options);
90
+ }
91
+ toJSON() {
92
+ return { ...this };
93
+ }
94
+ }
95
+ const jsonSize = (value) => JSON.stringify(value).length;
96
+ async function* iterate(source) {
97
+ yield* source;
98
+ }
99
+ export const scoreDataset = (core, name, rubric, options = {}) => {
100
+ const { version, name: jobName, limit, ...request } = options;
101
+ const { wire, local } = toRubric(rubric);
102
+ if (wire.length === 0)
103
+ throw new GradUsageError("dataset.score() needs a Judge, Scorer, validator or Rubric.", "invalid_rubric");
104
+ return new Pending((async () => {
105
+ const run = await core.api.scoreDataset(name, {
106
+ rubric: wire,
107
+ ...(version !== undefined ? { version } : {}),
108
+ ...(jobName !== undefined ? { name: jobName } : {}),
109
+ ...(limit !== undefined ? { limit } : {}),
110
+ }, request);
111
+ return new DatasetScoring(core, run, local);
112
+ })());
113
+ };
114
+ const isoBound = (value) => (value instanceof Date ? value.toISOString() : value);
115
+ export const filterDataset = async (core, name, filter, options = {}) => {
116
+ const merged = typeof filter === "function" ? options : { ...filter, ...options };
117
+ const { scores, metadata, createdAfter, createdBefore, ids, version, name: viewName, ...request } = merged;
118
+ let pinned = version;
119
+ let selected = ids;
120
+ if (typeof filter === "function") {
121
+ pinned = version ?? (await core.api.getDataset(name, request)).version;
122
+ selected = [];
123
+ for await (const record of new Dataset(core, { name }).records({ version: pinned, ...request })) {
124
+ if (record.id !== undefined && (await filter(record)))
125
+ selected.push(record.id);
126
+ }
127
+ }
128
+ const after = isoBound(createdAfter);
129
+ const before = isoBound(createdBefore);
130
+ const body = {
131
+ ...(scores !== undefined ? { scores } : {}),
132
+ ...(metadata !== undefined ? { metadata } : {}),
133
+ ...(after !== undefined ? { createdAfter: after } : {}),
134
+ ...(before !== undefined ? { createdBefore: before } : {}),
135
+ ...(selected !== undefined ? { ids: selected } : {}),
136
+ ...(pinned !== undefined ? { version: pinned } : {}),
137
+ ...(viewName !== undefined ? { name: viewName } : {}),
138
+ };
139
+ return new Dataset(core, await core.api.filterDataset(name, body, request));
140
+ };
141
+ export const pushRecords = async (core, name, records, options = {}) => {
142
+ const { metadata, batchSize = DEFAULT_BATCH, maxBatchBytes = DEFAULT_BATCH_BYTES, ...request } = options;
143
+ let source;
144
+ if (typeof records === "string") {
145
+ if (!isNodeRuntime())
146
+ throw new GradUsageError("Pushing a file path needs Node.js; pass records in a browser.", "node_only");
147
+ const { readJsonl } = await import("../node/files.js");
148
+ source = readJsonl(records);
149
+ }
150
+ else {
151
+ source = iterate(records);
152
+ }
153
+ let batch = [];
154
+ let bytes = 0;
155
+ let result;
156
+ let first = true;
157
+ const flush = async () => {
158
+ if (batch.length === 0)
159
+ return;
160
+ result = await core.api.pushDatasetRecords(name, { records: batch, ...(first && metadata !== undefined ? { metadata } : {}) }, request);
161
+ first = false;
162
+ batch = [];
163
+ bytes = 0;
164
+ };
165
+ for await (const record of source) {
166
+ const size = jsonSize(record);
167
+ if (batch.length > 0 && (batch.length >= batchSize || bytes + size > maxBatchBytes))
168
+ await flush();
169
+ batch.push(record);
170
+ bytes += size;
171
+ }
172
+ await flush();
173
+ if (!result)
174
+ throw new GradUsageError(`No records to push to dataset '${name}'.`, "empty_push");
175
+ return result;
176
+ };
177
+ const importFile = async (core, name, path, options) => {
178
+ if (!isNodeRuntime())
179
+ throw new GradUsageError("importFile needs Node.js (it reads the file from disk).", "node_only");
180
+ const { connector, format, ...request } = options;
181
+ const { describeFile } = await import("../node/files.js");
182
+ const file = await describeFile(path);
183
+ const ticket = await core.api.createUpload({ purpose: "dataset_import", filename: file.filename, sizeBytes: file.sizeBytes, sha256: file.sha256 }, request);
184
+ const put = await core.upload(ticket.url, ticket.headers, file.blob, request);
185
+ await put.cancel();
186
+ const job = await core.api.createDatasetImport(name, {
187
+ source: { kind: "upload", uploadId: ticket.uploadId, ...(format !== undefined ? { format } : {}) },
188
+ ...(connector !== undefined ? { connector } : {}),
189
+ }, request);
190
+ return new ImportJob(core, job);
191
+ };
192
+ const hfColumns = (options) => {
193
+ const columns = { ...(options.columns ?? {}) };
194
+ for (const key of ["messages", "prompt", "completion", "chosen", "rejected", "answer", "query", "positive"]) {
195
+ const value = options[key];
196
+ if (value !== undefined)
197
+ columns[key] = value;
198
+ }
199
+ return columns;
200
+ };
201
+ const importHf = async (core, name, repo, options) => {
202
+ const columns = hfColumns(options);
203
+ const job = await core.api.createDatasetImport(name, {
204
+ source: {
205
+ kind: "hf",
206
+ repo,
207
+ ...(options.split !== undefined ? { split: options.split } : {}),
208
+ ...(options.subset !== undefined ? { config: options.subset } : {}),
209
+ ...(options.revision !== undefined ? { revision: options.revision } : {}),
210
+ ...(options.limit !== undefined ? { limit: options.limit } : {}),
211
+ ...(Object.keys(columns).length > 0 ? { columns } : {}),
212
+ ...(options.secret !== undefined ? { secret: secretName(options.secret) } : {}),
213
+ },
214
+ ...(options.connector !== undefined ? { connector: options.connector } : {}),
215
+ });
216
+ return new ImportJob(core, job);
217
+ };
218
+ export const hfDatasetName = (repo, split = "train") => `${repo}-${split}`
219
+ .toLowerCase()
220
+ .replace(/[^a-z0-9._-]+/g, "-")
221
+ .replace(/^[^a-z0-9]+/, "")
222
+ .slice(0, 64)
223
+ .replace(/[-.]+$/, "");
224
+ export class DatasetsResource {
225
+ core;
226
+ constructor(core) {
227
+ this.core = core;
228
+ }
229
+ /**
230
+ * Imports a built-in benchmark (`gsm8k`, `mmlu`, `mmlu_pro`, `arc_challenge`)
231
+ * from Hugging Face at a pinned revision with fixed prompts; an eval on it
232
+ * without a rubric uses the benchmark's answer check.
233
+ */
234
+ async fromBenchmark(benchmark, options = {}) {
235
+ const { limit, name, wait, ...waitOptions } = options;
236
+ const target = name ?? (limit !== undefined ? `${benchmark}-${limit}` : benchmark);
237
+ const job = await this.core.api.createDatasetImport(target, {
238
+ source: { kind: "benchmark", benchmark, ...(limit !== undefined ? { limit } : {}) },
239
+ connector: "auto",
240
+ });
241
+ if (wait !== false)
242
+ await new ImportJob(this.core, job).wait(waitOptions);
243
+ return this.get(target);
244
+ }
245
+ /** Creates an empty dataset (409 ConflictError if the name exists). */
246
+ async create(name, options = {}) {
247
+ const { metadata, ...request } = options;
248
+ return new Dataset(this.core, await this.core.api.createDataset({ name, ...(metadata !== undefined ? { metadata } : {}) }, request));
249
+ }
250
+ async get(name, options) {
251
+ return new Dataset(this.core, await this.core.api.getDataset(name, options));
252
+ }
253
+ list(options = {}) {
254
+ const { limit, ...request } = options;
255
+ return new Paginator(async (cursor) => {
256
+ const page = await this.core.api.listDatasets({ ...(limit !== undefined ? { limit } : {}), ...(cursor ? { cursor } : {}) }, request);
257
+ return { data: page.data.map((d) => new Dataset(this.core, d)), nextCursor: page.nextCursor };
258
+ }, request.signal);
259
+ }
260
+ /** Pushes records (or a JSONL path in Node), creating the dataset if needed. Large inputs go in batches. */
261
+ async push(name, records, options) {
262
+ return new Dataset(this.core, await pushRecords(this.core, name, records, options));
263
+ }
264
+ records(name, options = {}) {
265
+ return new Dataset(this.core, { name }).records(options);
266
+ }
267
+ render(name, options = {}, request) {
268
+ return this.core.api.renderDataset(name, options, request);
269
+ }
270
+ /** See `Dataset.score`. */
271
+ score(name, rubric, options = {}) {
272
+ return scoreDataset(this.core, datasetName(name), rubric, options);
273
+ }
274
+ /** See `Dataset.filter`. */
275
+ filter(name, filter, options = {}) {
276
+ return filterDataset(this.core, datasetName(name), filter, options);
277
+ }
278
+ importFile(name, path, options = {}) {
279
+ return new Pending(importFile(this.core, datasetName(name), path, options));
280
+ }
281
+ /**
282
+ * Imports a Hugging Face dataset into a new (or existing) dataset and waits
283
+ * for it: `await grad.datasets.fromHf("openai/gsm8k", { subset: "main", prompt: "question", answer: "answer" })`.
284
+ */
285
+ async fromHf(repo, options = {}) {
286
+ const name = options.name ?? hfDatasetName(repo, options.split);
287
+ try {
288
+ await this.core.api.createDataset({ name, metadata: { source: `hf:${repo}` } });
289
+ }
290
+ catch (error) {
291
+ if (error.status !== 409)
292
+ throw error;
293
+ }
294
+ const { timeoutMs, signal, pollIntervalMs, maxPollIntervalMs, ...rest } = options;
295
+ const job = await importHf(this.core, name, repo, rest);
296
+ await job.wait({ timeoutMs, signal, pollIntervalMs, maxPollIntervalMs });
297
+ return this.get(name);
298
+ }
299
+ }
300
+ export class ImportsResource {
301
+ core;
302
+ constructor(core) {
303
+ this.core = core;
304
+ }
305
+ async get(id, options) {
306
+ return new ImportJob(this.core, await this.core.api.getImport(id, options));
307
+ }
308
+ list(options = {}) {
309
+ const { limit, ...request } = options;
310
+ return new Paginator(async (cursor) => {
311
+ const page = await this.core.api.listImports({ ...(limit !== undefined ? { limit } : {}), ...(cursor ? { cursor } : {}) }, request);
312
+ return { data: page.data.map((j) => new ImportJob(this.core, j)), nextCursor: page.nextCursor };
313
+ }, request.signal);
314
+ }
315
+ async wait(id, options) {
316
+ return (await this.get(id)).wait(options);
317
+ }
318
+ }
@@ -0,0 +1,110 @@
1
+ import type { EvalOutput, EvalRun, EvalStatus, EvalTaskOutcome, PlanEvalResponse } 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, type ScoreFn } from "../rubrics.js";
8
+ import { type ArtifactRef } from "./artifacts.js";
9
+ import { Dataset, type DatasetRef } from "./datasets.js";
10
+ export declare const TERMINAL_EVAL_STATUSES: readonly EvalStatus[];
11
+ export interface EvalParams {
12
+ name?: string;
13
+ models: ArtifactRef[];
14
+ baseline?: ArtifactRef;
15
+ dataset: DatasetRef;
16
+ datasetVersion?: number;
17
+ /** Server-side checks, judges, and local functions (scored by `wait()` in this process). */
18
+ rubric?: RubricInput;
19
+ samples?: number;
20
+ temperature?: number;
21
+ maxTokens?: number;
22
+ limit?: number;
23
+ passThreshold?: number | null;
24
+ }
25
+ export interface EvalWaitOptions extends WaitOptions {
26
+ /** Local scorer functions, when the eval was created elsewhere (e.g. by another process). */
27
+ rubric?: RubricInput;
28
+ onStatus?: (status: EvalStatus, evalRun: Eval) => void | Promise<void>;
29
+ }
30
+ /** Failing tasks of an eval; `toDataset()` saves their records for the next training round. */
31
+ export declare class EvalFailures {
32
+ #private;
33
+ readonly evalId: string;
34
+ readonly data: EvalTaskOutcome[];
35
+ constructor(core: Core, evalId: string, data: EvalTaskOutcome[]);
36
+ get length(): number;
37
+ [Symbol.iterator](): Iterator<EvalTaskOutcome>;
38
+ /** Pushes the failing records (deduplicated by task) to `name`, creating it if needed. */
39
+ toDataset(name: string, options?: {
40
+ metadata?: Record<string, unknown>;
41
+ } & RequestOptions): Promise<Dataset>;
42
+ }
43
+ /** A standalone evaluation. `wait()` also runs your local scorers when the server asks for them. */
44
+ export interface Eval extends EvalRun {
45
+ }
46
+ export declare class Eval {
47
+ #private;
48
+ constructor(core: Core, data: EvalRun, local?: Map<string, ScoreFn>);
49
+ refresh(options?: RequestOptions): Promise<this>;
50
+ /**
51
+ * Waits for `completed`. While the eval is `awaiting_scores`,
52
+ * pulls the outputs your local scorers have not scored yet, scores them here
53
+ * and posts the scores. Throws EvalFailedError on `failed`/`cancelled`.
54
+ */
55
+ wait(options?: EvalWaitOptions): Promise<this>;
56
+ private scoreLocal;
57
+ cancel(options?: RequestOptions): Promise<this>;
58
+ /** Failing tasks (score below `threshold`, default the eval's pass threshold). */
59
+ failures(options?: {
60
+ model?: string;
61
+ threshold?: number;
62
+ } & RequestOptions): Promise<EvalFailures>;
63
+ results(options?: {
64
+ model?: string;
65
+ limit?: number;
66
+ } & RequestOptions): Paginator<EvalTaskOutcome>;
67
+ /** A plain-text table: model, overall, 95% CI, pass@k, delta vs baseline, tasks, errors, cost. */
68
+ summaryTable(): string;
69
+ toJSON(): EvalRun;
70
+ }
71
+ export type PendingEval = Pending<Eval, Eval, EvalWaitOptions>;
72
+ /**
73
+ * A `dataset.score(...)` job (an eval in mode `score`). `wait()` runs local
74
+ * scorers when asked and resolves to the dataset with the new scores.
75
+ */
76
+ export declare class DatasetScoring {
77
+ #private;
78
+ readonly eval: Eval;
79
+ constructor(core: Core, data: EvalRun, local?: Map<string, ScoreFn>);
80
+ get id(): string;
81
+ get status(): EvalStatus;
82
+ wait(options?: EvalWaitOptions): Promise<Dataset>;
83
+ }
84
+ export type PendingScoring = Pending<DatasetScoring, Dataset, EvalWaitOptions>;
85
+ export declare class EvalsResource {
86
+ private readonly core;
87
+ constructor(core: Core);
88
+ /** Estimates tasks, model and judge calls, and cost; nothing runs. */
89
+ plan(params: EvalParams, options?: RequestOptions): Promise<PlanEvalResponse>;
90
+ /** Starts an eval: `await` it for the Eval, or chain `.wait()` (which also runs local scorers). */
91
+ create(params: EvalParams, options?: RequestOptions): PendingEval;
92
+ get(id: string, options?: RequestOptions): Promise<Eval>;
93
+ list(options?: {
94
+ limit?: number;
95
+ } & RequestOptions): Paginator<Eval>;
96
+ wait(id: string, options?: EvalWaitOptions): Promise<Eval>;
97
+ cancel(id: string, options?: RequestOptions): Promise<Eval>;
98
+ failures(id: string, options?: {
99
+ model?: string;
100
+ threshold?: number;
101
+ } & RequestOptions): Promise<EvalFailures>;
102
+ results(id: string, options?: {
103
+ model?: string;
104
+ limit?: number;
105
+ } & RequestOptions): Paginator<EvalTaskOutcome>;
106
+ outputs(id: string, options?: {
107
+ model?: string;
108
+ limit?: number;
109
+ } & RequestOptions): Paginator<EvalOutput>;
110
+ }
@@ -0,0 +1,258 @@
1
+ import { LIST_EVAL_OUTPUTS_LIMIT_MAX } from "../generated/client.js";
2
+ import { APIUserAbortError } from "../transport.js";
3
+ import { EvalFailedError, GradUsageError } from "../errors.js";
4
+ import { collect, pages, Paginator } from "../pagination.js";
5
+ import { Pending } from "../pending.js";
6
+ import { pollUntil } from "../polling.js";
7
+ import { toRubric } from "../rubrics.js";
8
+ import { artifactRef } from "./artifacts.js";
9
+ import { Dataset, datasetName, pushRecords } from "./datasets.js";
10
+ export const TERMINAL_EVAL_STATUSES = ["completed", "failed", "cancelled"];
11
+ const buildEvalBody = (params) => {
12
+ const rubric = params.rubric !== undefined ? toRubric(params.rubric) : undefined;
13
+ if (params.models.length === 0)
14
+ throw new GradUsageError("evals need at least one model.", "invalid_eval");
15
+ return {
16
+ body: {
17
+ models: params.models.map(artifactRef),
18
+ ...(params.name !== undefined ? { name: params.name } : {}),
19
+ ...(params.baseline !== undefined ? { baseline: artifactRef(params.baseline) } : {}),
20
+ dataset: datasetName(params.dataset),
21
+ ...(params.datasetVersion !== undefined ? { datasetVersion: params.datasetVersion } : {}),
22
+ ...(rubric ? { rubric: rubric.wire } : {}),
23
+ ...(params.samples !== undefined ? { samples: params.samples } : {}),
24
+ ...(params.temperature !== undefined ? { temperature: params.temperature } : {}),
25
+ ...(params.maxTokens !== undefined ? { maxTokens: params.maxTokens } : {}),
26
+ ...(params.limit !== undefined ? { limit: params.limit } : {}),
27
+ ...(params.passThreshold !== undefined ? { passThreshold: params.passThreshold } : {}),
28
+ },
29
+ local: rubric?.local ?? new Map(),
30
+ };
31
+ };
32
+ const toScore = (name, value) => {
33
+ const score = typeof value === "boolean" ? (value ? 1 : 0) : value;
34
+ if (typeof score !== "number" || !Number.isFinite(score)) {
35
+ throw new GradUsageError(`Scorer '${name}' returned ${String(value)}; return a finite number in [0, 1] or a boolean.`, "invalid_score");
36
+ }
37
+ return score;
38
+ };
39
+ const pct = (x) => `${(x * 100).toFixed(1)}%`;
40
+ /** Failing tasks of an eval; `toDataset()` saves their records for the next training round. */
41
+ export class EvalFailures {
42
+ #core;
43
+ evalId;
44
+ data;
45
+ constructor(core, evalId, data) {
46
+ this.#core = core;
47
+ this.evalId = evalId;
48
+ this.data = data;
49
+ }
50
+ get length() {
51
+ return this.data.length;
52
+ }
53
+ [Symbol.iterator]() {
54
+ return this.data[Symbol.iterator]();
55
+ }
56
+ /** Pushes the failing records (deduplicated by task) to `name`, creating it if needed. */
57
+ async toDataset(name, options = {}) {
58
+ const seen = new Set();
59
+ const records = [];
60
+ for (const outcome of this.data) {
61
+ if (seen.has(outcome.taskId))
62
+ continue;
63
+ seen.add(outcome.taskId);
64
+ records.push(outcome.record);
65
+ }
66
+ if (records.length === 0)
67
+ throw new GradUsageError(`Eval ${this.evalId} has no failures to save.`, "empty_push");
68
+ const { metadata, ...request } = options;
69
+ return new Dataset(this.#core, await pushRecords(this.#core, name, records, { ...request, metadata: { source: `eval:${this.evalId}`, ...(metadata ?? {}) } }));
70
+ }
71
+ }
72
+ export class Eval {
73
+ #core;
74
+ #local;
75
+ constructor(core, data, local = new Map()) {
76
+ this.#core = core;
77
+ this.#local = local;
78
+ Object.assign(this, data);
79
+ }
80
+ async refresh(options) {
81
+ Object.assign(this, await this.#core.api.getEval(this.id, options));
82
+ return this;
83
+ }
84
+ /**
85
+ * Waits for `completed`. While the eval is `awaiting_scores`,
86
+ * pulls the outputs your local scorers have not scored yet, scores them here
87
+ * and posts the scores. Throws EvalFailedError on `failed`/`cancelled`.
88
+ */
89
+ async wait(options = {}) {
90
+ if (options.rubric !== undefined) {
91
+ for (const [name, fn] of toRubric(options.rubric).local)
92
+ this.#local.set(name, fn);
93
+ }
94
+ let lastStatus;
95
+ await pollUntil(`eval ${this.id}`, (signal) => this.#core.api.getEval(this.id, { signal }), (ev) => TERMINAL_EVAL_STATUSES.includes(ev.status), options, this.#core.poll, async (ev) => {
96
+ Object.assign(this, ev);
97
+ if (ev.status !== lastStatus) {
98
+ lastStatus = ev.status;
99
+ await options.onStatus?.(ev.status, this);
100
+ }
101
+ if (ev.status === "awaiting_scores")
102
+ await this.scoreLocal(options.signal);
103
+ });
104
+ if (this.status === "failed" || this.status === "cancelled")
105
+ throw new EvalFailedError(this);
106
+ return this;
107
+ }
108
+ async scoreLocal(signal) {
109
+ const missing = this.localScorers.filter((name) => !this.#local.has(name));
110
+ if (missing.length > 0) {
111
+ throw new GradUsageError(`Eval ${this.id} needs local scores for ${missing.join(", ")}, but no function was given. Pass the same Rubric: ev.wait({ rubric }).`, "missing_local_scorer");
112
+ }
113
+ for (const name of this.localScorers) {
114
+ const fn = this.#local.get(name);
115
+ const scored = new Set();
116
+ while (true) {
117
+ if (signal?.aborted)
118
+ throw new APIUserAbortError(`Stopped scoring eval ${this.id}.`, { code: "aborted", cause: signal.reason });
119
+ const page = await this.#core.api.listEvalOutputs(this.id, { missingScorer: name, limit: LIST_EVAL_OUTPUTS_LIMIT_MAX }, { signal });
120
+ if (page.data.length === 0)
121
+ break;
122
+ if (page.data.some((out) => scored.has(out.id))) {
123
+ throw new GradUsageError(`Eval ${this.id}: the server still lists outputs already scored by '${name}'; stopping instead of re-posting.`, "score_not_recorded");
124
+ }
125
+ const scores = [];
126
+ for (const out of page.data) {
127
+ const value = await fn(out.output, {
128
+ output: out.output,
129
+ expectedOutput: out.expectedOutput,
130
+ record: out.record,
131
+ input: out.input,
132
+ model: out.model,
133
+ taskId: out.taskId,
134
+ sampleIndex: out.sampleIndex,
135
+ });
136
+ scores.push({ outputId: out.id, scorer: name, score: toScore(name, value) });
137
+ scored.add(out.id);
138
+ }
139
+ const posted = await this.#core.api.postEvalScores(this.id, { scores }, { signal });
140
+ if (posted.status !== "awaiting_scores")
141
+ return;
142
+ }
143
+ }
144
+ }
145
+ async cancel(options) {
146
+ Object.assign(this, await this.#core.api.cancelEval(this.id, options));
147
+ return this;
148
+ }
149
+ /** Failing tasks (score below `threshold`, default the eval's pass threshold). */
150
+ async failures(options = {}) {
151
+ return new EvalsResource(this.#core).failures(this.id, options);
152
+ }
153
+ results(options = {}) {
154
+ return new EvalsResource(this.#core).results(this.id, options);
155
+ }
156
+ /** A plain-text table: model, overall, 95% CI, pass@k, delta vs baseline, tasks, errors, cost. */
157
+ summaryTable() {
158
+ const ks = [...new Set(this.summary.flatMap((s) => Object.keys(s.passAtK)))].sort();
159
+ const header = ["model", "overall", "95% CI", ...ks, ...(this.baseline ? [`vs ${this.baseline}`] : []), "tasks", "errors", "$/1k tasks"];
160
+ const rows = this.summary.map((s) => [
161
+ s.model,
162
+ pct(s.overall),
163
+ `${pct(s.ciLow)}-${pct(s.ciHigh)}`,
164
+ ...ks.map((k) => (s.passAtK[k] === undefined ? "-" : pct(s.passAtK[k]))),
165
+ ...(this.baseline
166
+ ? [
167
+ s.model === this.baseline || !s.vsBaseline
168
+ ? "baseline"
169
+ : `${s.vsBaseline.delta >= 0 ? "+" : ""}${pct(s.vsBaseline.delta)} (${pct(s.vsBaseline.ciLow)}..${pct(s.vsBaseline.ciHigh)})`,
170
+ ]
171
+ : []),
172
+ String(s.tasks),
173
+ String(s.errors),
174
+ s.costPer1kTasksUsd === null ? "-" : `$${s.costPer1kTasksUsd.toFixed(2)}`,
175
+ ]);
176
+ const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length)));
177
+ const line = (cells) => cells.map((c, i) => c.padEnd(widths[i] ?? 0)).join(" ").trimEnd();
178
+ return [line(header), line(widths.map((w) => "-".repeat(w))), ...rows.map(line)].join("\n");
179
+ }
180
+ toJSON() {
181
+ return { ...this };
182
+ }
183
+ }
184
+ /**
185
+ * A `dataset.score(...)` job (an eval in mode `score`). `wait()` runs local
186
+ * scorers when asked and resolves to the dataset with the new scores.
187
+ */
188
+ export class DatasetScoring {
189
+ #core;
190
+ eval;
191
+ constructor(core, data, local = new Map()) {
192
+ this.#core = core;
193
+ this.eval = new Eval(core, data, local);
194
+ }
195
+ get id() {
196
+ return this.eval.id;
197
+ }
198
+ get status() {
199
+ return this.eval.status;
200
+ }
201
+ async wait(options = {}) {
202
+ await this.eval.wait(options);
203
+ return new Dataset(this.#core, await this.#core.api.getDataset(this.eval.taskSource.dataset, options));
204
+ }
205
+ }
206
+ export class EvalsResource {
207
+ core;
208
+ constructor(core) {
209
+ this.core = core;
210
+ }
211
+ /** Estimates tasks, model and judge calls, and cost; nothing runs. */
212
+ async plan(params, options) {
213
+ return this.core.api.planEval(buildEvalBody(params).body, options);
214
+ }
215
+ /** Starts an eval: `await` it for the Eval, or chain `.wait()` (which also runs local scorers). */
216
+ create(params, options) {
217
+ return new Pending((async () => {
218
+ const { body, local } = buildEvalBody(params);
219
+ return new Eval(this.core, await this.core.api.createEval(body, options), local);
220
+ })());
221
+ }
222
+ async get(id, options) {
223
+ return new Eval(this.core, await this.core.api.getEval(id, options));
224
+ }
225
+ list(options = {}) {
226
+ const { limit, ...request } = options;
227
+ return new Paginator(async (cursor) => {
228
+ const page = await this.core.api.listEvals({ ...(limit !== undefined ? { limit } : {}), ...(cursor ? { cursor } : {}) }, request);
229
+ return { data: page.data.map((e) => new Eval(this.core, e)), nextCursor: page.nextCursor };
230
+ }, request.signal);
231
+ }
232
+ async wait(id, options) {
233
+ return (await this.get(id)).wait(options);
234
+ }
235
+ async cancel(id, options) {
236
+ return new Eval(this.core, await this.core.api.cancelEval(id, options));
237
+ }
238
+ async failures(id, options = {}) {
239
+ const { model, threshold, ...request } = options;
240
+ const fetchPage = (cursor) => this.core.api.listEvalFailures(id, { ...(model !== undefined ? { model } : {}), ...(threshold !== undefined ? { threshold } : {}), ...(cursor ? { cursor } : {}) }, request);
241
+ const data = await collect(pages(fetchPage, request.signal));
242
+ return new EvalFailures(this.core, id, data);
243
+ }
244
+ results(id, options = {}) {
245
+ const { model, limit, ...request } = options;
246
+ return new Paginator(async (cursor) => {
247
+ const page = await this.core.api.listEvalResults(id, { ...(model !== undefined ? { model } : {}), ...(limit !== undefined ? { limit } : {}), ...(cursor ? { cursor } : {}) }, request);
248
+ return { data: page.data, nextCursor: page.nextCursor };
249
+ }, request.signal);
250
+ }
251
+ outputs(id, options = {}) {
252
+ const { model, limit, ...request } = options;
253
+ return new Paginator(async (cursor) => {
254
+ const page = await this.core.api.listEvalOutputs(id, { ...(model !== undefined ? { model } : {}), ...(limit !== undefined ? { limit } : {}), ...(cursor ? { cursor } : {}) }, request);
255
+ return { data: page.data, nextCursor: page.nextCursor };
256
+ }, request.signal);
257
+ }
258
+ }