@gradiated/grad 0.2.0-alpha.1 → 0.2.0-alpha.2
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/README.md +13 -1
- package/dist/generated/client.d.ts +18 -1
- package/dist/generated/client.js +29 -1
- package/dist/generated/models.d.ts +123 -0
- package/dist/generated/models.js +2 -0
- package/dist/index.d.ts +2 -2
- package/dist/resources/runs.d.ts +22 -3
- package/dist/resources/runs.js +91 -7
- package/dist/transport.d.ts +3 -1
- package/dist/transport.js +8 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -28,6 +28,18 @@ await run.deploy(); // Cloud; a self-hosted server raises DeployUnavailableError
|
|
|
28
28
|
await grad.deployments.rollback("support-router"); // back to the previous artifact
|
|
29
29
|
```
|
|
30
30
|
|
|
31
|
+
Follow a run's lifecycle as typed events (narrow on `ev.type`; reconnects are
|
|
32
|
+
invisible, the stream ends after `completed`):
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
for await (const ev of grad.runs.events(run.id, { follow: true })) {
|
|
36
|
+
if (ev.type === "phase") console.log(ev.phase, ev.workersOnline ?? "");
|
|
37
|
+
else if (ev.type === "metric") console.log(ev.step, ev.metric?.loss);
|
|
38
|
+
else if (ev.type === "attempt") console.log(ev.message); // "attempt 1 interrupted at step 120: the GPU was reclaimed; resuming from step 120 on a new worker"
|
|
39
|
+
}
|
|
40
|
+
// or: await run.wait({ onEvent: (ev) => ..., onStatus: (status, run) => console.log(status, run.phase) })
|
|
41
|
+
```
|
|
42
|
+
|
|
31
43
|
Self-hosted servers do not serve models: `artifact.download(dest)` and serve
|
|
32
44
|
the bundle yourself (vLLM, SGLang). Production feedback reaches training
|
|
33
45
|
through your observability tool and `grad sources`, not through this SDK.
|
|
@@ -43,7 +55,7 @@ real `grad-server` started by `tests/harness/stack.ts`.
|
|
|
43
55
|
| Area | API |
|
|
44
56
|
| --- | --- |
|
|
45
57
|
| 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()` |
|
|
58
|
+
| Runs | `grad.runs.plan/create/get/list/cancel/resume`, `run.wait({ onEvent, onMetric, onStatus })`, `run.events({ follow: true })` (typed lifecycle events: phase, metric, checkpoint, attempt, warning, log, completed), `run.metrics({ follow: true })` (SSE with reconnect), `run.checkpoints()`, `checkpoint.promote()` |
|
|
47
59
|
| Recipes | `recipes.sft/dpo/router/decisionModel/cartridge/embedding/distill/rewardModel`, `rollouts`, `adapters`, `splits`, `Context` |
|
|
48
60
|
| Artifacts | `grad.artifacts.get/list/stream`, `artifact.download(dest)` (streams to disk, verifies SHA-256) |
|
|
49
61
|
| Deploy (Cloud) | `grad.deploy()` / `run.deploy()` / `artifact.deploy()` (= `grad.deployments.create`), `grad.deployments.get/list/rollback` |
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type CodecTable, type RawResponse, type RequestOptions, type ServerSentEvent, type SSEOptions, type StreamOptions, type TransportLike } from "../transport.js";
|
|
2
|
-
import type { ApiKey, Artifact, Checkpoint, CreateApiKeyRequest, CreateDatasetRequest, CreateImportRequest, CreateSourceRequest, CreateUploadRequest, CreatedApiKey, Dataset, DatasetRecordsPage, DeployArtifactRequest, Deployment, DeploymentStatus, EmbedRequest, EmbedResponse, EvalOutput, EvalRun, EvalTaskOutcome, FilterDatasetRequest, ImportJob, MetricsPage, PlanEvalRequest, PlanEvalResponse, PlanRunRequest, PlanRunResponse, PostEvalScoresRequest, PostEvalScoresResponse, PromoteCheckpointRequest, PushDatasetRequest, RecordFeedbackRequest, RecordFeedbackResponse, RenderDatasetRequest, RenderDatasetResponse, ResumeRunRequest, RouteRequest, RouteResponse, Run, ScoreDatasetRequest, Secret, SetSecretRequest, Source, SyncSourceRequest, TrainableModel, UploadTicket, UsageRecord } from "./models.js";
|
|
2
|
+
import type { ApiKey, Artifact, Checkpoint, CreateApiKeyRequest, CreateDatasetRequest, CreateImportRequest, CreateSourceRequest, CreateUploadRequest, CreatedApiKey, Dataset, DatasetRecordsPage, DeployArtifactRequest, Deployment, DeploymentStatus, EmbedRequest, EmbedResponse, EvalOutput, EvalRun, EvalTaskOutcome, FilterDatasetRequest, ImportJob, MetricsPage, PlanEvalRequest, PlanEvalResponse, PlanRunRequest, PlanRunResponse, PostEvalScoresRequest, PostEvalScoresResponse, PromoteCheckpointRequest, PushDatasetRequest, RecordFeedbackRequest, RecordFeedbackResponse, RenderDatasetRequest, RenderDatasetResponse, ResumeRunRequest, RouteRequest, RouteResponse, Run, RunEventsPage, ScoreDatasetRequest, Secret, SetSecretRequest, Source, SyncSourceRequest, TrainableModel, UploadTicket, UsageRecord } from "./models.js";
|
|
3
3
|
/** Which wire keys are renamed to camelCase, per schema (user-keyed maps are left verbatim). */
|
|
4
4
|
export declare const CODEC: CodecTable;
|
|
5
5
|
export interface ListApiKeysParams {
|
|
@@ -118,6 +118,11 @@ export type ListRunCheckpointsResponse = {
|
|
|
118
118
|
/** Pass back as `cursor` for the next page; null on the last page (every list endpoint). */
|
|
119
119
|
nextCursor: string | null;
|
|
120
120
|
};
|
|
121
|
+
export interface ListRunEventsParams {
|
|
122
|
+
cursor?: string | undefined;
|
|
123
|
+
/** Page size (default 1000). Values above 5000 are clamped to 5000. */
|
|
124
|
+
limit?: number | undefined;
|
|
125
|
+
}
|
|
121
126
|
export interface ListRunMetricsParams {
|
|
122
127
|
cursor?: string | undefined;
|
|
123
128
|
afterStep?: number | undefined;
|
|
@@ -187,6 +192,8 @@ export declare const LIST_EVALS_LIMIT_MAX = 200;
|
|
|
187
192
|
export declare const LIST_IMPORTS_LIMIT_MAX = 200;
|
|
188
193
|
/** Largest `limit` accepted by `listRunCheckpoints` (the server clamps larger values). */
|
|
189
194
|
export declare const LIST_RUN_CHECKPOINTS_LIMIT_MAX = 200;
|
|
195
|
+
/** Largest `limit` accepted by `listRunEvents` (the server clamps larger values). */
|
|
196
|
+
export declare const LIST_RUN_EVENTS_LIMIT_MAX = 5000;
|
|
190
197
|
/** Largest `limit` accepted by `listRunMetrics` (the server clamps larger values). */
|
|
191
198
|
export declare const LIST_RUN_METRICS_LIMIT_MAX = 5000;
|
|
192
199
|
/** Largest `limit` accepted by `listRuns` (the server clamps larger values). */
|
|
@@ -411,6 +418,16 @@ export declare class ApiClient {
|
|
|
411
418
|
* `GET /v1/runs/{id}/checkpoints`
|
|
412
419
|
*/
|
|
413
420
|
listRunCheckpoints(id: string, params?: ListRunCheckpointsParams, options?: RequestOptions): Promise<ListRunCheckpointsResponse>;
|
|
421
|
+
/**
|
|
422
|
+
* A run's lifecycle events (phases, metrics, checkpoints, attempts, warnings, logs)
|
|
423
|
+
*
|
|
424
|
+
* `GET /v1/runs/{id}/events`
|
|
425
|
+
*/
|
|
426
|
+
listRunEvents(id: string, params?: ListRunEventsParams, options?: RequestOptions): Promise<RunEventsPage>;
|
|
427
|
+
/**
|
|
428
|
+
* A run's lifecycle events (phases, metrics, checkpoints, attempts, warnings, logs) (Server-Sent Events; one connection, resume with `lastEventId`)
|
|
429
|
+
*/
|
|
430
|
+
listRunEventsStream(id: string, params?: ListRunEventsParams, options?: SSEOptions): AsyncGenerator<ServerSentEvent, void, undefined>;
|
|
414
431
|
/**
|
|
415
432
|
* Training step metrics as JSON pages, or a live SSE stream
|
|
416
433
|
*
|
package/dist/generated/client.js
CHANGED
|
@@ -6,10 +6,13 @@ export const CODEC = {
|
|
|
6
6
|
"AdapterSpec": { u: { o: { o: [["mergeOnExport", "merge_on_export", 0], ["numTokens", "num_tokens", 0]] } } },
|
|
7
7
|
"ApiKey": { o: [["workspaceId", "workspace_id", 0], ["createdAt", "created_at", 0], ["revokedAt", "revoked_at", 0]] },
|
|
8
8
|
"Artifact": { o: [["workspaceId", "workspace_id", 0], ["runId", "run_id", 0], ["checkpointId", "checkpoint_id", 0], ["baseModel", "base_model", 0], ["recipeKind", "recipe_kind", 0], ["sizeBytes", "size_bytes", 0], ["evalReport", "eval_report", "EvalReport"], ["createdAt", "created_at", 0]] },
|
|
9
|
+
"AttemptEvent": { o: [["runId", "run_id", 0], ["resumeStep", "resume_step", 0], ["maxAttempts", "max_attempts", 0]] },
|
|
9
10
|
"BaseArtifact": { o: [["recipeKind", "recipe_kind", 0]] },
|
|
10
11
|
"ChatMessage": { o: [["toolCalls", "tool_calls", 0], ["toolCallId", "tool_call_id", 0]] },
|
|
11
12
|
"Checkpoint": { o: [["workspaceId", "workspace_id", 0], ["runId", "run_id", 0], ["evalScore", "eval_score", 0], ["sizeBytes", "size_bytes", 0], ["expiresAt", "expires_at", 0], ["createdAt", "created_at", 0]] },
|
|
12
13
|
"CheckpointEvalResult": { o: [["checkpointId", "checkpoint_id", 0], ["evalId", "eval_id", 0], ["datasetVersion", "dataset_version", 0], ["costUsd", "cost_usd", 0]] },
|
|
14
|
+
"CheckpointEvent": { o: [["runId", "run_id", 0], ["checkpointId", "checkpoint_id", 0], ["evalScore", "eval_score", 0]] },
|
|
15
|
+
"CompletedEvent": { o: [["runId", "run_id", 0], ["run", "run", "Run"]] },
|
|
13
16
|
"CreateImportRequest": { o: [["source", "source", "ImportSource"]] },
|
|
14
17
|
"CreateUploadRequest": { o: [["sizeBytes", "size_bytes", 0]] },
|
|
15
18
|
"CreatedApiKey": { o: [["key", "key", "ApiKey"]] },
|
|
@@ -29,13 +32,17 @@ export const CODEC = {
|
|
|
29
32
|
"FeedbackEventInput": { o: [["inferenceId", "inference_id", 0], ["sessionId", "session_id", 0], ["deploymentName", "deployment_name", 0], ["idempotencyKey", "idempotency_key", 0], ["expectedOutput", "expected_output", 0]] },
|
|
30
33
|
"FeedbackRecord": { o: [["workspaceId", "workspace_id", 0], ["inferenceId", "inference_id", 0], ["sessionId", "session_id", 0], ["deploymentName", "deployment_name", 0], ["idempotencyKey", "idempotency_key", 0], ["expectedOutput", "expected_output", 0], ["createdAt", "created_at", 0]] },
|
|
31
34
|
"FilterDatasetRequest": { o: [["createdAfter", "created_after", 0], ["createdBefore", "created_before", 0]] },
|
|
35
|
+
"GpuInfo": { o: [["memoryGb", "memory_gb", 0]] },
|
|
32
36
|
"ImportJob": { o: [["workspaceId", "workspace_id", 0], ["importedCount", "imported_count", 0], ["droppedCount", "dropped_count", 0], ["detectedScores", "detected_scores", 0], ["dropReasons", "drop_reasons", 0], ["datasetVersion", "dataset_version", 0], ["createdAt", "created_at", 0], ["updatedAt", "updated_at", 0]] },
|
|
33
37
|
"ImportSource": { u: { o: { o: [["uploadId", "upload_id", 0]] } } },
|
|
38
|
+
"LogEvent": { o: [["runId", "run_id", 0]] },
|
|
34
39
|
"LoggerSpec": { u: { o: { o: [["runName", "run_name", 0], ["trackingUri", "tracking_uri", 0]] } } },
|
|
35
40
|
"LossSpec": { u: { o: { o: [["topK", "top_k", 0]] } } },
|
|
41
|
+
"MetricEvent": { o: [["runId", "run_id", 0], ["metric", "metric", "MetricPoint"]] },
|
|
36
42
|
"MetricPoint": { o: [["evalLoss", "eval_loss", 0], ["evalMetrics", "eval_metrics", 0], ["gradNorm", "grad_norm", 0], ["tokensPerSec", "tokens_per_sec", 0], ["costUsd", "cost_usd", 0]] },
|
|
37
43
|
"MetricsPage": { o: [["runId", "run_id", 0], ["data", "data", { a: "MetricPoint" }], ["nextCursor", "next_cursor", 0], ["tailCursor", "tail_cursor", 0]] },
|
|
38
44
|
"OptimizerSpec": { o: [["weightDecay", "weight_decay", 0], ["gradClip", "grad_clip", 0]] },
|
|
45
|
+
"PhaseEvent": { o: [["runId", "run_id", 0], ["workersOnline", "workers_online", 0], ["gpu", "gpu", "GpuInfo"]] },
|
|
39
46
|
"PlanEvalRequest": { o: [["datasetVersion", "dataset_version", 0], ["maxTokens", "max_tokens", 0], ["passThreshold", "pass_threshold", 0]] },
|
|
40
47
|
"PlanEvalResponse": { o: [["taskSourceKind", "task_source_kind", 0], ["datasetVersion", "dataset_version", 0], ["estimatedTasks", "estimated_tasks", 0], ["estimatedModelCalls", "estimated_model_calls", 0], ["estimatedJudgeCalls", "estimated_judge_calls", 0], ["estimatedCostUsd", "estimated_cost_usd", 0], ["judgeModels", "judge_models", 0], ["localScorers", "local_scorers", 0], ["passThreshold", "pass_threshold", 0]] },
|
|
41
48
|
"PlanRunRequest": { o: [["recipe", "recipe", "RecipeSpec"], ["split", "split", "SplitSpec"], ["maxCostUsd", "max_cost_usd", 0]] },
|
|
@@ -54,7 +61,10 @@ export const CODEC = {
|
|
|
54
61
|
"RouteRequest": { o: [["messages", "messages", { a: "ChatMessage" }], ["sessionId", "session_id", 0]] },
|
|
55
62
|
"RouteResponse": { o: [["inferenceId", "inference_id", 0], ["artifactId", "artifact_id", 0], ["isExploration", "is_exploration", 0]] },
|
|
56
63
|
"RouterParetoSummary": { o: [["targetMaxDrop", "target_max_drop", 0], ["routedQuality", "routed_quality", 0], ["qualityDrop", "quality_drop", 0], ["qualityDropCi95", "quality_drop_ci95", 0], ["offloadRate", "offload_rate", 0], ["costSavingsPct", "cost_savings_pct", 0]] },
|
|
57
|
-
"Run": { o: [["workspaceId", "workspace_id", 0], ["datasetId", "dataset_id", 0], ["datasetName", "dataset_name", 0], ["datasetVersion", "dataset_version", 0], ["recipeKind", "recipe_kind", 0], ["resolvedConfig", "resolved_config", "ResolvedRunConfig"], ["maxCostUsd", "max_cost_usd", 0], ["pricePerMillionTokens", "price_per_million_tokens", 0], ["tokensProcessed", "tokens_processed", 0], ["costUsd", "cost_usd", 0], ["currentStep", "current_step", 0], ["totalSteps", "total_steps", 0], ["maxAttempts", "max_attempts", 0], ["latestMetric", "latest_metric", "MetricPoint"], ["evalReport", "eval_report", "EvalReport"], ["checkpointEvals", "checkpoint_evals", { a: "CheckpointEvalResult" }], ["artifactId", "artifact_id", 0], ["createdAt", "created_at", 0], ["updatedAt", "updated_at", 0], ["finishedAt", "finished_at", 0]] },
|
|
64
|
+
"Run": { o: [["workspaceId", "workspace_id", 0], ["datasetId", "dataset_id", 0], ["datasetName", "dataset_name", 0], ["datasetVersion", "dataset_version", 0], ["recipeKind", "recipe_kind", 0], ["resolvedConfig", "resolved_config", "ResolvedRunConfig"], ["maxCostUsd", "max_cost_usd", 0], ["pricePerMillionTokens", "price_per_million_tokens", 0], ["tokensProcessed", "tokens_processed", 0], ["costUsd", "cost_usd", 0], ["currentStep", "current_step", 0], ["totalSteps", "total_steps", 0], ["maxAttempts", "max_attempts", 0], ["phaseSince", "phase_since", 0], ["lastInterruption", "last_interruption", "RunInterruption"], ["workersOnline", "workers_online", 0], ["latestMetric", "latest_metric", "MetricPoint"], ["evalReport", "eval_report", "EvalReport"], ["checkpointEvals", "checkpoint_evals", { a: "CheckpointEvalResult" }], ["artifactId", "artifact_id", 0], ["createdAt", "created_at", 0], ["updatedAt", "updated_at", 0], ["finishedAt", "finished_at", 0]] },
|
|
65
|
+
"RunEvent": { d: ["type", { "phase": "PhaseEvent", "metric": "MetricEvent", "checkpoint": "CheckpointEvent", "attempt": "AttemptEvent", "warning": "WarningEvent", "log": "LogEvent", "completed": "CompletedEvent" }] },
|
|
66
|
+
"RunEventsPage": { o: [["runId", "run_id", 0], ["data", "data", { a: "RunEvent" }], ["nextCursor", "next_cursor", 0], ["tailCursor", "tail_cursor", 0]] },
|
|
67
|
+
"RunInterruption": { o: [["resumeStep", "resume_step", 0]] },
|
|
58
68
|
"Secret": { o: [["workspaceId", "workspace_id", 0], ["allowedHosts", "allowed_hosts", 0], ["createdAt", "created_at", 0], ["updatedAt", "updated_at", 0]] },
|
|
59
69
|
"SetSecretRequest": { o: [["allowedHosts", "allowed_hosts", 0]] },
|
|
60
70
|
"Source": { o: [["workspaceId", "workspace_id", 0], ["nextSyncAt", "next_sync_at", 0], ["pausedReason", "paused_reason", 0], ["lastError", "last_error", 0], ["lastErrorAt", "last_error_at", 0], ["consecutiveFailures", "consecutive_failures", 0], ["pendingFull", "pending_full", 0], ["lastSyncedAt", "last_synced_at", 0], ["lastSync", "last_sync", "SourceSync"], ["createdAt", "created_at", 0], ["updatedAt", "updated_at", 0]] },
|
|
@@ -65,6 +75,7 @@ export const CODEC = {
|
|
|
65
75
|
"TrajectoryOutput": { o: [["turns", "turns", { a: "ChatMessage" }]] },
|
|
66
76
|
"UploadTicket": { o: [["uploadId", "upload_id", 0], ["expiresAt", "expires_at", 0]] },
|
|
67
77
|
"UsageRecord": { o: [["refId", "ref_id", 0], ["tokensFrom", "tokens_from", 0], ["tokensThrough", "tokens_through", 0], ["costUsd", "cost_usd", 0], ["priceVersion", "price_version", 0], ["idempotencyKey", "idempotency_key", 0], ["createdAt", "created_at", 0]] },
|
|
78
|
+
"WarningEvent": { o: [["runId", "run_id", 0]] },
|
|
68
79
|
};
|
|
69
80
|
/** Largest `limit` accepted by `listApiKeys` (the server clamps larger values). */
|
|
70
81
|
export const LIST_API_KEYS_LIMIT_MAX = 200;
|
|
@@ -88,6 +99,8 @@ export const LIST_EVALS_LIMIT_MAX = 200;
|
|
|
88
99
|
export const LIST_IMPORTS_LIMIT_MAX = 200;
|
|
89
100
|
/** Largest `limit` accepted by `listRunCheckpoints` (the server clamps larger values). */
|
|
90
101
|
export const LIST_RUN_CHECKPOINTS_LIMIT_MAX = 200;
|
|
102
|
+
/** Largest `limit` accepted by `listRunEvents` (the server clamps larger values). */
|
|
103
|
+
export const LIST_RUN_EVENTS_LIMIT_MAX = 5000;
|
|
91
104
|
/** Largest `limit` accepted by `listRunMetrics` (the server clamps larger values). */
|
|
92
105
|
export const LIST_RUN_METRICS_LIMIT_MAX = 5000;
|
|
93
106
|
/** Largest `limit` accepted by `listRuns` (the server clamps larger values). */
|
|
@@ -416,6 +429,21 @@ export class ApiClient {
|
|
|
416
429
|
const data = await this.transport.json({ method: "GET", path: `/v1/runs/${encodePathParam(id, "id")}/checkpoints`, query: [["limit", params?.limit], ["cursor", params?.cursor]] }, options);
|
|
417
430
|
return convertKeys(CODEC, { o: [["data", "data", { a: "Checkpoint" }], ["nextCursor", "next_cursor", 0]] }, data, "decode");
|
|
418
431
|
}
|
|
432
|
+
/**
|
|
433
|
+
* A run's lifecycle events (phases, metrics, checkpoints, attempts, warnings, logs)
|
|
434
|
+
*
|
|
435
|
+
* `GET /v1/runs/{id}/events`
|
|
436
|
+
*/
|
|
437
|
+
async listRunEvents(id, params, options) {
|
|
438
|
+
const data = await this.transport.json({ method: "GET", path: `/v1/runs/${encodePathParam(id, "id")}/events`, query: [["cursor", params?.cursor], ["limit", params?.limit]] }, options);
|
|
439
|
+
return convertKeys(CODEC, "RunEventsPage", data, "decode");
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* A run's lifecycle events (phases, metrics, checkpoints, attempts, warnings, logs) (Server-Sent Events; one connection, resume with `lastEventId`)
|
|
443
|
+
*/
|
|
444
|
+
listRunEventsStream(id, params, options) {
|
|
445
|
+
return this.transport.sse({ method: "GET", path: `/v1/runs/${encodePathParam(id, "id")}/events`, query: [["cursor", params?.cursor], ["limit", params?.limit]] }, options);
|
|
446
|
+
}
|
|
419
447
|
/**
|
|
420
448
|
* Training step metrics as JSON pages, or a live SSE stream
|
|
421
449
|
*
|
|
@@ -39,6 +39,22 @@ export interface Artifact {
|
|
|
39
39
|
/** Artifact format when this checkpoint is exportable (promotable); null for training state only. */
|
|
40
40
|
export type ArtifactFormat = "peft_lora" | "merged_safetensors" | "prefix_kv" | "cartridge" | "encoder_safetensors" | "router_bundle" | "decision_bundle" | "reward_bundle" | "reference";
|
|
41
41
|
export declare const ArtifactFormatValues: readonly ["peft_lora", "merged_safetensors", "prefix_kv", "cartridge", "encoder_safetensors", "router_bundle", "decision_bundle", "reward_bundle", "reference"];
|
|
42
|
+
export interface AttemptEvent {
|
|
43
|
+
type: "attempt";
|
|
44
|
+
runId: string;
|
|
45
|
+
/** Position in the run's event sequence (the SSE event id; pass it as Last-Event-ID or `cursor` to resume). `completed` repeats the last stored seq. */
|
|
46
|
+
seq: number;
|
|
47
|
+
attempt: number;
|
|
48
|
+
timestamp: string;
|
|
49
|
+
/** started: a worker claimed attempt N (resume_step: the checkpoint it resumes from). interrupted: attempt N ended without a result at `step` (resume_step: where the next attempt resumes). gave_up: no attempts left; the run failed. */
|
|
50
|
+
event: "started" | "interrupted" | "gave_up";
|
|
51
|
+
reason: InterruptionReason | null;
|
|
52
|
+
step: number | null;
|
|
53
|
+
/** Checkpoint step to resume from; null starts from scratch. */
|
|
54
|
+
resumeStep: number | null;
|
|
55
|
+
maxAttempts: number;
|
|
56
|
+
message: string;
|
|
57
|
+
}
|
|
42
58
|
/** Continued training: the artifact whose adapter the run starts from (recipe.model was an artifact reference). */
|
|
43
59
|
export interface BaseArtifact {
|
|
44
60
|
id: string;
|
|
@@ -84,6 +100,28 @@ export interface CheckpointEvalResult {
|
|
|
84
100
|
costUsd: number;
|
|
85
101
|
error: string | null;
|
|
86
102
|
}
|
|
103
|
+
export interface CheckpointEvent {
|
|
104
|
+
type: "checkpoint";
|
|
105
|
+
runId: string;
|
|
106
|
+
/** Position in the run's event sequence (the SSE event id; pass it as Last-Event-ID or `cursor` to resume). `completed` repeats the last stored seq. */
|
|
107
|
+
seq: number;
|
|
108
|
+
attempt: number;
|
|
109
|
+
timestamp: string;
|
|
110
|
+
step: number;
|
|
111
|
+
checkpointId: string;
|
|
112
|
+
evalScore: number | null;
|
|
113
|
+
format: ArtifactFormat | null;
|
|
114
|
+
}
|
|
115
|
+
export interface CompletedEvent {
|
|
116
|
+
type: "completed";
|
|
117
|
+
runId: string;
|
|
118
|
+
/** Position in the run's event sequence (the SSE event id; pass it as Last-Event-ID or `cursor` to resume). `completed` repeats the last stored seq. */
|
|
119
|
+
seq: number;
|
|
120
|
+
attempt: number;
|
|
121
|
+
timestamp: string;
|
|
122
|
+
status: RunStatus;
|
|
123
|
+
run: Run;
|
|
124
|
+
}
|
|
87
125
|
export interface CreateApiKeyRequest {
|
|
88
126
|
name: string;
|
|
89
127
|
scopes: Array<ApiKeyScope>;
|
|
@@ -439,6 +477,11 @@ export interface FilterDatasetRequest {
|
|
|
439
477
|
/** Name of the view. Default: `<dataset>-f-<hash of source, version and filter>`, so the same filter returns the same view. */
|
|
440
478
|
name?: string | undefined;
|
|
441
479
|
}
|
|
480
|
+
/** starting: the claiming worker's GPU (null without one, e.g. the reference backend). Never the worker id or host. */
|
|
481
|
+
export interface GpuInfo {
|
|
482
|
+
name: string;
|
|
483
|
+
memoryGb: number;
|
|
484
|
+
}
|
|
442
485
|
export interface HfColumnMapping {
|
|
443
486
|
messages?: string | undefined;
|
|
444
487
|
prompt?: string | undefined;
|
|
@@ -491,6 +534,19 @@ export type ImportSource = {
|
|
|
491
534
|
};
|
|
492
535
|
export type ImportStatus = "queued" | "running" | "completed" | "failed";
|
|
493
536
|
export declare const ImportStatusValues: readonly ["queued", "running", "completed", "failed"];
|
|
537
|
+
/** Why an attempt ended without a result: lease_lost (the worker was lost: it stopped heartbeating after a crash, kill or network failure), compute_reclaimed (the GPU was reclaimed; the worker saved a checkpoint when it had time and handed the run back), worker_error (the worker hit an unexpected error and handed the run back), oom (CUDA out of memory). */
|
|
538
|
+
export type InterruptionReason = "lease_lost" | "compute_reclaimed" | "worker_error" | "oom";
|
|
539
|
+
export declare const InterruptionReasonValues: readonly ["lease_lost", "compute_reclaimed", "worker_error", "oom"];
|
|
540
|
+
export interface LogEvent {
|
|
541
|
+
type: "log";
|
|
542
|
+
runId: string;
|
|
543
|
+
/** Position in the run's event sequence (the SSE event id; pass it as Last-Event-ID or `cursor` to resume). `completed` repeats the last stored seq. */
|
|
544
|
+
seq: number;
|
|
545
|
+
attempt: number;
|
|
546
|
+
timestamp: string;
|
|
547
|
+
step: number | null;
|
|
548
|
+
message: string;
|
|
549
|
+
}
|
|
494
550
|
export type LoggerSpec = {
|
|
495
551
|
kind: "wandb";
|
|
496
552
|
project: string;
|
|
@@ -523,6 +579,16 @@ export type LossSpec = {
|
|
|
523
579
|
kind: "top_k_kl_distill";
|
|
524
580
|
topK?: number | undefined;
|
|
525
581
|
};
|
|
582
|
+
export interface MetricEvent {
|
|
583
|
+
type: "metric";
|
|
584
|
+
runId: string;
|
|
585
|
+
/** Position in the run's event sequence (the SSE event id; pass it as Last-Event-ID or `cursor` to resume). `completed` repeats the last stored seq. */
|
|
586
|
+
seq: number;
|
|
587
|
+
attempt: number;
|
|
588
|
+
timestamp: string;
|
|
589
|
+
step: number;
|
|
590
|
+
metric: MetricPoint | null;
|
|
591
|
+
}
|
|
526
592
|
export interface MetricPoint {
|
|
527
593
|
seq: number;
|
|
528
594
|
attempt: number;
|
|
@@ -555,6 +621,22 @@ export interface OptimizerSpec {
|
|
|
555
621
|
/** Max global gradient norm; 0 disables clipping. */
|
|
556
622
|
gradClip?: number | undefined;
|
|
557
623
|
}
|
|
624
|
+
export interface PhaseEvent {
|
|
625
|
+
type: "phase";
|
|
626
|
+
runId: string;
|
|
627
|
+
/** Position in the run's event sequence (the SSE event id; pass it as Last-Event-ID or `cursor` to resume). `completed` repeats the last stored seq. */
|
|
628
|
+
seq: number;
|
|
629
|
+
attempt: number;
|
|
630
|
+
timestamp: string;
|
|
631
|
+
phase: RunPhase;
|
|
632
|
+
/** Training step when the phase began (0 before training; the resume step on a resumed attempt). */
|
|
633
|
+
step: number;
|
|
634
|
+
/** queued and waiting_for_compute: workers of this job kind holding a lease (all busy; an idle worker would have claimed the run). */
|
|
635
|
+
workersOnline: number | null;
|
|
636
|
+
/** queued and waiting_for_compute: true when workers scale from zero (KEDA), so one is starting rather than missing. */
|
|
637
|
+
autoscaling: boolean | null;
|
|
638
|
+
gpu: GpuInfo | null;
|
|
639
|
+
}
|
|
558
640
|
export interface PlanEvalRequest {
|
|
559
641
|
name?: string | undefined;
|
|
560
642
|
models: Array<string>;
|
|
@@ -843,8 +925,17 @@ export interface Run {
|
|
|
843
925
|
costUsd: number;
|
|
844
926
|
currentStep: number;
|
|
845
927
|
totalSteps: number;
|
|
928
|
+
/** Attempts started so far (every start on a worker counts, including ones whose GPU was reclaimed). */
|
|
846
929
|
attempt: number;
|
|
930
|
+
/** The run fails once this many attempts end without a result (lost worker, worker error, OOM). Attempts whose GPU was reclaimed don't count toward it. */
|
|
847
931
|
maxAttempts: number;
|
|
932
|
+
phase: ("queued" | "waiting_for_compute" | "starting" | "loading_model" | "training" | "evaluating" | "checkpointing" | "uploading" | "completing") | null;
|
|
933
|
+
phaseSince: string | null;
|
|
934
|
+
lastInterruption: RunInterruption | null;
|
|
935
|
+
/** While queued: workers of this kind holding a lease (all busy). Null otherwise. */
|
|
936
|
+
workersOnline: number | null;
|
|
937
|
+
/** While queued: true when workers scale from zero (KEDA), so a worker is starting. Null otherwise. */
|
|
938
|
+
autoscaling: boolean | null;
|
|
848
939
|
latestMetric: MetricPoint | null;
|
|
849
940
|
evalReport: EvalReport | null;
|
|
850
941
|
/** recipe.evals results, one per finished eval: a checkpoint (step) on a dataset. */
|
|
@@ -855,6 +946,28 @@ export interface Run {
|
|
|
855
946
|
updatedAt: string;
|
|
856
947
|
finishedAt: string | null;
|
|
857
948
|
}
|
|
949
|
+
/** One event of a run's lifecycle, discriminated by `type`. `completed` is always last. */
|
|
950
|
+
export type RunEvent = PhaseEvent | MetricEvent | CheckpointEvent | AttemptEvent | WarningEvent | LogEvent | CompletedEvent;
|
|
951
|
+
export interface RunEventsPage {
|
|
952
|
+
runId: string;
|
|
953
|
+
status: RunStatus;
|
|
954
|
+
data: Array<RunEvent>;
|
|
955
|
+
/** Pass back as `cursor` for the next page; null on the last page (every list endpoint). */
|
|
956
|
+
nextCursor: string | null;
|
|
957
|
+
/** Cursor after the newest event returned so far; pass it back as `cursor` to poll for later events. */
|
|
958
|
+
tailCursor: string;
|
|
959
|
+
}
|
|
960
|
+
export interface RunInterruption {
|
|
961
|
+
attempt: number;
|
|
962
|
+
reason: InterruptionReason;
|
|
963
|
+
step: number;
|
|
964
|
+
resumeStep: number | null;
|
|
965
|
+
at: string;
|
|
966
|
+
message: string;
|
|
967
|
+
}
|
|
968
|
+
/** Where a run is in its lifecycle (on a Run: the latest phase; once the run is terminal, status is authoritative and phase is the last one reached). queued, waiting_for_compute (queued for longer than the server's threshold with no worker claiming it) and starting (a worker claimed it) come from the server; the worker reports the rest. training, evaluating and checkpointing repeat. */
|
|
969
|
+
export type RunPhase = "queued" | "waiting_for_compute" | "starting" | "loading_model" | "training" | "evaluating" | "checkpointing" | "uploading" | "completing";
|
|
970
|
+
export declare const RunPhaseValues: readonly ["queued", "waiting_for_compute", "starting", "loading_model", "training", "evaluating", "checkpointing", "uploading", "completing"];
|
|
858
971
|
/** stopped_budget: the run reached its max_cost_usd (resume with a higher cap). stopped_balance: the workspace ran out of balance on Cloud (top up, then resume; the cap is unchanged). Both keep their checkpoints. */
|
|
859
972
|
export type RunStatus = "queued" | "running" | "completed" | "failed" | "cancelled" | "stopped_budget" | "stopped_balance";
|
|
860
973
|
export declare const RunStatusValues: readonly ["queued", "running", "completed", "failed", "cancelled", "stopped_budget", "stopped_balance"];
|
|
@@ -996,3 +1109,13 @@ export interface UsageRecord {
|
|
|
996
1109
|
idempotencyKey: string;
|
|
997
1110
|
createdAt: string;
|
|
998
1111
|
}
|
|
1112
|
+
export interface WarningEvent {
|
|
1113
|
+
type: "warning";
|
|
1114
|
+
runId: string;
|
|
1115
|
+
/** Position in the run's event sequence (the SSE event id; pass it as Last-Event-ID or `cursor` to resume). `completed` repeats the last stored seq. */
|
|
1116
|
+
seq: number;
|
|
1117
|
+
attempt: number;
|
|
1118
|
+
timestamp: string;
|
|
1119
|
+
step: number | null;
|
|
1120
|
+
message: string;
|
|
1121
|
+
}
|
package/dist/generated/models.js
CHANGED
|
@@ -5,5 +5,7 @@ export const ArtifactFormatValues = ["peft_lora", "merged_safetensors", "prefix_
|
|
|
5
5
|
export const EvalModeValues = ["eval", "score"];
|
|
6
6
|
export const EvalStatusValues = ["queued", "running", "awaiting_scores", "completed", "failed", "cancelled"];
|
|
7
7
|
export const ImportStatusValues = ["queued", "running", "completed", "failed"];
|
|
8
|
+
export const InterruptionReasonValues = ["lease_lost", "compute_reclaimed", "worker_error", "oom"];
|
|
8
9
|
export const RecipeKindValues = ["sft", "dpo", "router", "decision", "cartridge", "embedding", "distill", "reward", "grpo"];
|
|
10
|
+
export const RunPhaseValues = ["queued", "waiting_for_compute", "starting", "loading_model", "training", "evaluating", "checkpointing", "uploading", "completing"];
|
|
9
11
|
export const RunStatusValues = ["queued", "running", "completed", "failed", "cancelled", "stopped_budget", "stopped_balance"];
|
package/dist/index.d.ts
CHANGED
|
@@ -12,8 +12,8 @@ export { Dataset, DatasetsResource, ImportJob, ImportsResource, type DatasetRef,
|
|
|
12
12
|
export { DatasetScoring, Eval, EvalFailures, EvalsResource, type PendingScoring, TERMINAL_EVAL_STATUSES, type EvalParams, type EvalWaitOptions, type PendingEval } from "./resources/evals.js";
|
|
13
13
|
export { KeysResource, ModelsResource, UsageResource } from "./resources/misc.js";
|
|
14
14
|
export { SecretRef, SecretsResource, Source, SourcesResource, sources, type AddSourceOptions, type GradiatedOptions, type ProviderOptions, type SecretLike, type SourceProvider, } from "./resources/sources.js";
|
|
15
|
-
export { Checkpoint, CheckpointsResource, Run, RunPlan, RunsResource, TERMINAL_RUN_STATUSES, type CompletedRun, type MetricsOptions, type PendingRun, type RunParams, type RunWaitOptions, } from "./resources/runs.js";
|
|
15
|
+
export { Checkpoint, CheckpointsResource, Run, RunPlan, RunsResource, TERMINAL_RUN_STATUSES, type CompletedRun, type EventsOptions, type MetricsOptions, type PendingRun, type RunParams, type RunWaitOptions, } from "./resources/runs.js";
|
|
16
16
|
export { ApiClient, LIST_API_KEYS_LIMIT_MAX, LIST_ARTIFACTS_LIMIT_MAX, LIST_DATASET_RECORDS_LIMIT_MAX, LIST_DATASETS_LIMIT_MAX, LIST_DEPLOYMENTS_LIMIT_MAX, LIST_EVAL_FAILURES_LIMIT_MAX, LIST_EVAL_OUTPUTS_LIMIT_MAX, LIST_EVAL_RESULTS_LIMIT_MAX, LIST_EVALS_LIMIT_MAX, LIST_IMPORTS_LIMIT_MAX, LIST_RUN_CHECKPOINTS_LIMIT_MAX, LIST_RUN_METRICS_LIMIT_MAX, LIST_RUNS_LIMIT_MAX, LIST_USAGE_LIMIT_MAX, } from "./generated/client.js";
|
|
17
17
|
export { newIdempotencyKey, SDK_VERSION, type RawResponse, type RequestOptions, type ServerSentEvent, type SSEOptions, type StreamOptions } from "./transport.js";
|
|
18
18
|
export type * as models from "./generated/models.js";
|
|
19
|
-
export type { AdapterSpec, ApiKey, ApiKeyScope, ChatMessage, CreatedApiKey, DatasetRecord, Deployment, DeploymentStatus, EvalModelSummary, EvalOutput, EvalReport, EvalRubricItem, EvalTaskOutcome, MetricPoint, PlanEvalResponse, RecipeSpec, ResolvedRunConfig, RouterParetoSummary, RunStatus, SplitSpec, TrainableModel, UsageRecord, } from "./generated/models.js";
|
|
19
|
+
export type { AdapterSpec, ApiKey, ApiKeyScope, ChatMessage, CreatedApiKey, DatasetRecord, Deployment, DeploymentStatus, EvalModelSummary, EvalOutput, EvalReport, EvalRubricItem, EvalTaskOutcome, AttemptEvent, CheckpointEvent, CompletedEvent, GpuInfo, InterruptionReason, LogEvent, MetricEvent, MetricPoint, PhaseEvent, PlanEvalResponse, RecipeSpec, ResolvedRunConfig, RouterParetoSummary, RunEvent, RunInterruption, RunPhase, RunStatus, SplitSpec, TrainableModel, UsageRecord, WarningEvent, } from "./generated/models.js";
|
package/dist/resources/runs.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Artifact as ArtifactData, Checkpoint as CheckpointData, Deployment, MetricPoint, PlanRunResponse, RecipeSpec, ResolvedRunConfig, Run as RunData, RunStatus, SplitSpec } from "../generated/models.js";
|
|
1
|
+
import type { Artifact as ArtifactData, Checkpoint as CheckpointData, Deployment, MetricPoint, PlanRunResponse, RecipeSpec, ResolvedRunConfig, Run as RunData, RunEvent, RunStatus, SplitSpec } from "../generated/models.js";
|
|
2
2
|
import { type RequestOptions } from "../transport.js";
|
|
3
3
|
import type { Core } from "../core.js";
|
|
4
4
|
import { Paginator } from "../pagination.js";
|
|
@@ -17,11 +17,19 @@ export interface RunParams {
|
|
|
17
17
|
maxCostUsd?: number;
|
|
18
18
|
}
|
|
19
19
|
export interface RunWaitOptions extends WaitOptions {
|
|
20
|
-
/**
|
|
20
|
+
/** Every lifecycle event while waiting (phases, metrics, checkpoints, attempts, warnings, logs, completed). */
|
|
21
|
+
onEvent?: (event: RunEvent) => void | Promise<void>;
|
|
22
|
+
/** Streams each metric point while waiting (from the run's event stream). */
|
|
21
23
|
onMetric?: (metric: MetricPoint) => void | Promise<void>;
|
|
22
|
-
/** Called with every status change. */
|
|
24
|
+
/** Called with every status or phase change. */
|
|
23
25
|
onStatus?: (status: RunStatus, run: Run) => void | Promise<void>;
|
|
24
26
|
}
|
|
27
|
+
export interface EventsOptions extends RequestOptions {
|
|
28
|
+
/** Keep the stream open until the run finishes (SSE; reconnects with Last-Event-ID). */
|
|
29
|
+
follow?: boolean;
|
|
30
|
+
/** Page size of the JSON pages (without `follow`). */
|
|
31
|
+
limit?: number;
|
|
32
|
+
}
|
|
25
33
|
export interface MetricsOptions extends RequestOptions {
|
|
26
34
|
/** Keep the stream open until the run finishes (SSE with automatic reconnect). */
|
|
27
35
|
follow?: boolean;
|
|
@@ -69,6 +77,15 @@ export declare class Run {
|
|
|
69
77
|
* with `Last-Event-ID` after drops, and ends when the run finishes.
|
|
70
78
|
*/
|
|
71
79
|
metrics(options?: MetricsOptions): AsyncGenerator<MetricPoint, void, undefined>;
|
|
80
|
+
/**
|
|
81
|
+
* The run's lifecycle events, typed by `type` (phase, metric, checkpoint,
|
|
82
|
+
* attempt, warning, log, completed). With `follow: true` this streams live
|
|
83
|
+
* over SSE, reconnects with `Last-Event-ID` after drops (never repeating an
|
|
84
|
+
* event) and ends after `completed`, which also refreshes this run.
|
|
85
|
+
*/
|
|
86
|
+
events(options?: EventsOptions): AsyncGenerator<RunEvent, void, undefined>;
|
|
87
|
+
/** Keeps this run's phase and status in step with the events it streams. */
|
|
88
|
+
private observe;
|
|
72
89
|
cancel(options?: RequestOptions): Promise<this>;
|
|
73
90
|
/** Re-queues a stopped run from its last checkpoint (raise `maxCostUsd` after a budget stop). */
|
|
74
91
|
resume(options?: {
|
|
@@ -108,6 +125,8 @@ export declare class RunsResource {
|
|
|
108
125
|
} & RequestOptions): Promise<Run>;
|
|
109
126
|
metrics(id: string, options?: MetricsOptions): AsyncGenerator<MetricPoint, void, undefined>;
|
|
110
127
|
checkpoints(id: string, options?: RequestOptions): Promise<Checkpoint[]>;
|
|
128
|
+
/** A run's lifecycle events; `for await (const ev of grad.runs.events(id, { follow: true }))`. */
|
|
129
|
+
events(id: string, options?: EventsOptions): AsyncGenerator<RunEvent, void, undefined>;
|
|
111
130
|
}
|
|
112
131
|
export declare class CheckpointsResource {
|
|
113
132
|
private readonly core;
|
package/dist/resources/runs.js
CHANGED
|
@@ -9,6 +9,8 @@ import { Artifact, deployArtifact, downloadArtifact } from "./artifacts.js";
|
|
|
9
9
|
import { datasetName } from "./datasets.js";
|
|
10
10
|
export const TERMINAL_RUN_STATUSES = ["completed", "failed", "cancelled", "stopped_budget", "stopped_balance"];
|
|
11
11
|
const isTerminal = (status) => TERMINAL_RUN_STATUSES.includes(status);
|
|
12
|
+
const RUN_EVENT_TYPES = new Set(["phase", "metric", "checkpoint", "attempt", "warning", "log", "completed"]);
|
|
13
|
+
const WAITING_PHASES = new Set(["queued", "waiting_for_compute"]);
|
|
12
14
|
export class RunPlan {
|
|
13
15
|
constructor(data) {
|
|
14
16
|
Object.assign(this, data);
|
|
@@ -31,6 +33,7 @@ const buildRunBody = async (params) => {
|
|
|
31
33
|
};
|
|
32
34
|
const decodeMetric = (data) => convertKeys(CODEC, "MetricPoint", JSON.parse(data), "decode");
|
|
33
35
|
const decodeRun = (data) => convertKeys(CODEC, "Run", JSON.parse(data), "decode");
|
|
36
|
+
const decodeEvent = (data) => convertKeys(CODEC, "RunEvent", JSON.parse(data), "decode");
|
|
34
37
|
export class Checkpoint {
|
|
35
38
|
#core;
|
|
36
39
|
constructor(core, data) {
|
|
@@ -67,14 +70,15 @@ export class Run {
|
|
|
67
70
|
* `stopped_budget` (resume with a raised cap) and `stopped_balance` (top up, then resume).
|
|
68
71
|
*/
|
|
69
72
|
async wait(options = {}) {
|
|
70
|
-
let
|
|
73
|
+
let last;
|
|
71
74
|
const notify = async () => {
|
|
72
|
-
|
|
73
|
-
|
|
75
|
+
const key = `${this.status}/${this.phase ?? ""}`;
|
|
76
|
+
if (key !== last) {
|
|
77
|
+
last = key;
|
|
74
78
|
await options.onStatus?.(this.status, this);
|
|
75
79
|
}
|
|
76
80
|
};
|
|
77
|
-
if (options.onMetric) {
|
|
81
|
+
if (options.onMetric || options.onEvent) {
|
|
78
82
|
await this.followUntilDone(options, notify);
|
|
79
83
|
}
|
|
80
84
|
else {
|
|
@@ -99,10 +103,14 @@ export class Run {
|
|
|
99
103
|
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
100
104
|
const timer = options.timeoutMs === undefined ? undefined : setTimeout(() => controller.abort(new WaitTimeoutError(`run ${this.id}`, options.timeoutMs ?? 0)), options.timeoutMs);
|
|
101
105
|
try {
|
|
102
|
-
for await (const
|
|
103
|
-
await options.
|
|
106
|
+
for await (const event of this.events({ follow: true, signal: controller.signal })) {
|
|
107
|
+
await options.onEvent?.(event);
|
|
108
|
+
if (event.type === "metric" && event.metric)
|
|
109
|
+
await options.onMetric?.(event.metric);
|
|
110
|
+
if (event.type === "phase")
|
|
111
|
+
await notify();
|
|
104
112
|
}
|
|
105
|
-
//
|
|
113
|
+
// events({ follow }) only returns after the final `completed` event, which updated this run.
|
|
106
114
|
await notify();
|
|
107
115
|
}
|
|
108
116
|
catch (error) {
|
|
@@ -160,6 +168,78 @@ export class Run {
|
|
|
160
168
|
await this.#core.poll.sleep(Math.min(500 * 2 ** Math.min(failures - 1, 4), 5_000), request.signal);
|
|
161
169
|
}
|
|
162
170
|
}
|
|
171
|
+
/**
|
|
172
|
+
* The run's lifecycle events, typed by `type` (phase, metric, checkpoint,
|
|
173
|
+
* attempt, warning, log, completed). With `follow: true` this streams live
|
|
174
|
+
* over SSE, reconnects with `Last-Event-ID` after drops (never repeating an
|
|
175
|
+
* event) and ends after `completed`, which also refreshes this run.
|
|
176
|
+
*/
|
|
177
|
+
async *events(options = {}) {
|
|
178
|
+
const { follow = false, limit, ...request } = options;
|
|
179
|
+
if (!follow) {
|
|
180
|
+
const fetchPage = (cursor) => this.#core.api.listRunEvents(this.id, { ...(cursor ? { cursor } : {}), ...(limit !== undefined ? { limit } : {}) }, request);
|
|
181
|
+
for await (const page of pages(fetchPage, request.signal)) {
|
|
182
|
+
for (const event of page.data) {
|
|
183
|
+
this.observe(event);
|
|
184
|
+
yield event;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
let lastEventId;
|
|
190
|
+
let lastSeq = 0;
|
|
191
|
+
let failures = 0;
|
|
192
|
+
while (true) {
|
|
193
|
+
try {
|
|
194
|
+
for await (const sse of this.#core.api.listRunEventsStream(this.id, {}, { ...request, ...(lastEventId !== undefined ? { lastEventId } : {}) })) {
|
|
195
|
+
failures = 0;
|
|
196
|
+
if (!RUN_EVENT_TYPES.has(sse.event))
|
|
197
|
+
continue;
|
|
198
|
+
const event = decodeEvent(sse.data);
|
|
199
|
+
if (event.type !== "completed") {
|
|
200
|
+
if (sse.id !== undefined)
|
|
201
|
+
lastEventId = sse.id;
|
|
202
|
+
if (event.seq <= lastSeq)
|
|
203
|
+
continue;
|
|
204
|
+
lastSeq = event.seq;
|
|
205
|
+
}
|
|
206
|
+
this.observe(event);
|
|
207
|
+
yield event;
|
|
208
|
+
if (event.type === "completed")
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
// The stream closed without `completed` (proxy timeout, deploy): reconnect.
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
if (request.signal?.aborted || !isTransient(error))
|
|
215
|
+
throw error;
|
|
216
|
+
}
|
|
217
|
+
failures += 1;
|
|
218
|
+
await this.#core.poll.sleep(Math.min(500 * 2 ** Math.min(failures - 1, 4), 5_000), request.signal);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
/** Keeps this run's phase and status in step with the events it streams. */
|
|
222
|
+
observe(event) {
|
|
223
|
+
if (event.type === "completed") {
|
|
224
|
+
this.update(event.run);
|
|
225
|
+
}
|
|
226
|
+
else if (event.type === "phase") {
|
|
227
|
+
this.phase = event.phase;
|
|
228
|
+
this.phaseSince = event.timestamp;
|
|
229
|
+
if (!isTerminal(this.status))
|
|
230
|
+
this.status = WAITING_PHASES.has(event.phase) ? "queued" : "running";
|
|
231
|
+
}
|
|
232
|
+
else if (event.type === "attempt" && event.event === "interrupted" && event.reason !== null) {
|
|
233
|
+
this.lastInterruption = {
|
|
234
|
+
attempt: event.attempt,
|
|
235
|
+
reason: event.reason,
|
|
236
|
+
step: event.step ?? 0,
|
|
237
|
+
resumeStep: event.resumeStep,
|
|
238
|
+
at: event.timestamp,
|
|
239
|
+
message: event.message,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
}
|
|
163
243
|
async cancel(options) {
|
|
164
244
|
this.update(await this.#core.api.cancelRun(this.id, options));
|
|
165
245
|
return this;
|
|
@@ -232,6 +312,10 @@ export class RunsResource {
|
|
|
232
312
|
checkpoints(id, options) {
|
|
233
313
|
return new Run(this.core, { id }).checkpoints(options);
|
|
234
314
|
}
|
|
315
|
+
/** A run's lifecycle events; `for await (const ev of grad.runs.events(id, { follow: true }))`. */
|
|
316
|
+
events(id, options) {
|
|
317
|
+
return new Run(this.core, { id }).events(options);
|
|
318
|
+
}
|
|
235
319
|
}
|
|
236
320
|
export class CheckpointsResource {
|
|
237
321
|
core;
|
package/dist/transport.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare const SDK_VERSION = "0.2.0-alpha.
|
|
1
|
+
export declare const SDK_VERSION = "0.2.0-alpha.2";
|
|
2
2
|
export declare const readEnv: (name: string) => string | undefined;
|
|
3
3
|
export interface FieldError {
|
|
4
4
|
field: string;
|
|
@@ -105,6 +105,8 @@ export type CodecNode = 0 | string | {
|
|
|
105
105
|
a?: CodecNode;
|
|
106
106
|
o?: CodecNode;
|
|
107
107
|
};
|
|
108
|
+
} | {
|
|
109
|
+
d: [string, Record<string, CodecNode>];
|
|
108
110
|
};
|
|
109
111
|
export type CodecTable = Record<string, CodecNode>;
|
|
110
112
|
/** Renames declared keys between camelCase and wire names; user-keyed maps stay verbatim. */
|
package/dist/transport.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* they retry like GETs), same-origin-only redirects, per-attempt timeouts
|
|
4
4
|
* that stop at the response headers for streams, SSE parsing, request ids,
|
|
5
5
|
* and the camelCase <-> wire key codec. Browser-safe: no Node imports. */
|
|
6
|
-
export const SDK_VERSION = "0.2.0-alpha.
|
|
6
|
+
export const SDK_VERSION = "0.2.0-alpha.2";
|
|
7
7
|
const nodeProcess = () => globalThis.process;
|
|
8
8
|
export const readEnv = (name) => {
|
|
9
9
|
const value = nodeProcess()?.env?.[name];
|
|
@@ -217,6 +217,13 @@ export const convertKeys = (table, node, value, direction) => {
|
|
|
217
217
|
}
|
|
218
218
|
return out;
|
|
219
219
|
}
|
|
220
|
+
if ("d" in node) {
|
|
221
|
+
if (!isObject(value))
|
|
222
|
+
return value;
|
|
223
|
+
const [tag, variants] = node.d;
|
|
224
|
+
const variant = variants[String(value[tag])];
|
|
225
|
+
return variant === undefined ? value : convertKeys(table, variant, value, direction);
|
|
226
|
+
}
|
|
220
227
|
if ("u" in node) {
|
|
221
228
|
if (Array.isArray(value) && node.u.a !== undefined) {
|
|
222
229
|
return convertKeys(table, node.u.a, value, direction);
|
package/package.json
CHANGED