@toloka-platform/sdk 0.27.0 → 0.28.0

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 (37) hide show
  1. package/README.md +5 -3
  2. package/dist/cli/toloka.js +179 -190
  3. package/dist/cli/toloka.js.jsc +0 -0
  4. package/dist/cli/toloka.js.jsc.sha256 +1 -1
  5. package/dist/cli/toloka.js.sha256 +1 -1
  6. package/examples/video-pair-rating/nodes/adjudicate/node.ts +1 -1
  7. package/examples/video-pair-rating/nodes/adjudicate_op/node.ts +1 -1
  8. package/examples/video-pair-rating/nodes/overall_preference_pick/node.ts +5 -1
  9. package/examples/video-pair-rating/nodes/rate_pair/node.ts +5 -1
  10. package/openapi/gen/api.schemas.ts +51 -758
  11. package/openapi/gen/api.ts +0 -860
  12. package/package.json +2 -2
  13. package/skills/catalog.json +6 -40
  14. package/skills/toloka-build/references/human-work.md +15 -6
  15. package/skills/toloka-build/references/local-setup.md +2 -2
  16. package/skills/toloka-build/references/workflow-and-cli.md +3 -22
  17. package/skills/toloka-get-started/SKILL.md +9 -13
  18. package/src/cli/analytics.ts +0 -31
  19. package/src/cli/auth.ts +15 -7
  20. package/src/cli/config.ts +67 -3
  21. package/src/cli/context.ts +3 -124
  22. package/src/cli/credentials.ts +11 -10
  23. package/src/cli/init.ts +1 -1
  24. package/src/cli/program.ts +0 -6
  25. package/src/cli/project.ts +9 -1
  26. package/src/client.ts +3 -261
  27. package/src/importer.ts +12 -2
  28. package/src/index.ts +0 -2
  29. package/src/pipeline-graph-v1.contract.json +130 -128
  30. package/skills/toloka-fine-tuning/SKILL.md +0 -177
  31. package/skills/toloka-gisting/SKILL.md +0 -186
  32. package/src/cli/batch-inference.ts +0 -267
  33. package/src/cli/commands/batch-inference.ts +0 -116
  34. package/src/cli/commands/models.ts +0 -121
  35. package/src/cli/commands/training.ts +0 -275
  36. package/src/cli/models.ts +0 -304
  37. package/src/cli/trainings.ts +0 -880
@@ -1,121 +0,0 @@
1
- import type { Command } from "commander";
2
- import { resolveContext, type CommandHost } from "../context";
3
- import {
4
- archiveModel,
5
- createModel,
6
- downloadModelVersion,
7
- getBaseModel,
8
- getModel,
9
- listBaseModels,
10
- listModels,
11
- listModelVersions,
12
- parseBaseModelId,
13
- } from "../models";
14
- import { assertProjectSelected } from "../project-context";
15
-
16
- export const registerModelCommands = (program: Command, host: CommandHost): void => {
17
- const { context, globals } = host;
18
-
19
- const baseModel = program
20
- .command("base-model")
21
- .description("inspect the global base model catalog");
22
- baseModel
23
- .command("list")
24
- .option("--json", "print JSON", false)
25
- .description("list base models")
26
- .action(async (options: { json: boolean }) => {
27
- const { client } = await resolveContext(globals(), context);
28
- await listBaseModels(client, { json: options.json }, context.io);
29
- });
30
- baseModel
31
- .command("get")
32
- .argument("<id>", "base model ID")
33
- .option("--json", "print JSON", false)
34
- .description("show one base model")
35
- .action(async (id: string, options: { json: boolean }) => {
36
- const { client } = await resolveContext(globals(), context);
37
- await getBaseModel(client, { id: parseBaseModelId(id), json: options.json }, context.io);
38
- });
39
-
40
- const model = program
41
- .command("model")
42
- .description("manage project Models and immutable versions");
43
- model
44
- .command("list")
45
- .option("--json", "print JSON", false)
46
- .description("list up to 100 Models owned by the selected project (first page only)")
47
- .action(async (options: { json: boolean }) => {
48
- const { client, projectId } = await resolveContext(globals(), context);
49
- assertProjectSelected(projectId);
50
- await listModels(client, { projectId, json: options.json }, context.io);
51
- });
52
- model
53
- .command("get")
54
- .argument("<name-or-id>", "project Model name or ID")
55
- .option("--json", "print JSON", false)
56
- .description("show one project Model")
57
- .action(async (nameOrId: string, options: { json: boolean }) => {
58
- const { client, projectId } = await resolveContext(globals(), context);
59
- assertProjectSelected(projectId);
60
- await getModel(client, { projectId, nameOrId, json: options.json }, context.io);
61
- });
62
- model
63
- .command("versions")
64
- .argument("<name-or-id>", "project Model name or ID")
65
- .option("--json", "print JSON", false)
66
- .description("list immutable versions of a model")
67
- .action(async (nameOrId: string, options: { json: boolean }) => {
68
- const { client, projectId } = await resolveContext(globals(), context);
69
- assertProjectSelected(projectId);
70
- await listModelVersions(client, { projectId, nameOrId, json: options.json }, context.io);
71
- });
72
- model
73
- .command("create")
74
- .argument("<name>", "new Model name")
75
- .requiredOption("--base <id>", "base model ID")
76
- .option("--description <text>", "Model description")
77
- .option("--json", "print JSON", false)
78
- .description("create project Model metadata without a Model Version")
79
- .action(
80
- async (name: string, options: { base: string; description?: string; json: boolean }) => {
81
- const { client, projectId } = await resolveContext(globals(), context);
82
- assertProjectSelected(projectId);
83
- await createModel(
84
- client,
85
- {
86
- projectId,
87
- name,
88
- description: options.description,
89
- baseModelId: parseBaseModelId(options.base),
90
- json: options.json,
91
- },
92
- context.io,
93
- );
94
- },
95
- );
96
- model
97
- .command("archive")
98
- .option("--json", "print JSON", false)
99
- .argument("<name-or-id>", "project Model name or ID")
100
- .description("archive a project Model")
101
- .action(async (nameOrId: string, options: { json: boolean }) => {
102
- const { client, projectId } = await resolveContext(globals(), context);
103
- assertProjectSelected(projectId);
104
- await archiveModel(client, { projectId, nameOrId, json: options.json }, context.io);
105
- });
106
-
107
- const modelVersion = model.command("version").description("manage one immutable Model Version");
108
- modelVersion
109
- .command("download")
110
- .argument("<model-version>", "Model Version ID or Model@name")
111
- .requiredOption("--out <directory>", "output directory")
112
- .description("download and verify Model Version content")
113
- .action(async (modelVersionId: string, options: { out: string }) => {
114
- const { client, projectId } = await resolveContext(globals(), context);
115
- await downloadModelVersion(
116
- client,
117
- { projectId, modelVersionId, out: options.out },
118
- context.io,
119
- );
120
- });
121
- };
@@ -1,275 +0,0 @@
1
- import type { Command } from "commander";
2
- import {
3
- partNames,
4
- positiveInteger,
5
- resolveContext,
6
- trainingBatchSize,
7
- trainingDraftOptions,
8
- trainingEpochs,
9
- trainingGistTokens,
10
- trainingLearningRate,
11
- trainingLoraRank,
12
- trainingMaxSequenceLength,
13
- trainingMethod,
14
- type CommandHost,
15
- type RawTrainingDraftOptions,
16
- } from "../context";
17
- import { parseBaseModelId } from "../models";
18
- import { assertProjectSelected } from "../project-context";
19
- import {
20
- cancelTrainingRun,
21
- createTraining,
22
- createTrainingRun,
23
- estimateTrainingCost,
24
- getTraining,
25
- getTrainingRun,
26
- listTrainingRuns,
27
- listTrainings,
28
- readTrainingRunLogs,
29
- readTrainingRunMetricHistory,
30
- readTrainingRunMetrics,
31
- resumeTrainingRun,
32
- updateTraining,
33
- } from "../trainings";
34
-
35
- export const registerTrainingCommands = (program: Command, host: CommandHost): void => {
36
- const { context, globals } = host;
37
- const training = program.command("training").description("manage project Training drafts");
38
- training
39
- .command("list")
40
- .option("--json", "print JSON", false)
41
- .description("list up to 100 active Trainings owned by the selected project (first page only)")
42
- .action(async (options: { json: boolean }) => {
43
- const { client, projectId } = await resolveContext(globals(), context);
44
- assertProjectSelected(projectId);
45
- await listTrainings(client, { projectId, json: options.json }, context.io);
46
- });
47
- training
48
- .command("get")
49
- .argument("<name-or-id>", "Training name or ID")
50
- .option("--json", "print JSON", false)
51
- .description("show one Training draft")
52
- .action(async (nameOrId: string, options: { json: boolean }) => {
53
- const { client, projectId } = await resolveContext(globals(), context);
54
- assertProjectSelected(projectId);
55
- await getTraining(client, { projectId, nameOrId, json: options.json }, context.io);
56
- });
57
- training
58
- .command("create")
59
- .argument("<name>", "new Training name")
60
- .option("--method <method>", "Training method: sft or gisting", trainingMethod, "sft")
61
- .option("--base-model <id>", "catalog Base Model source; pass exactly one of --base-model or --model-version", parseBaseModelId)
62
- .option("--model-version <id>", "exact Model Version source; pass exactly one of --base-model or --model-version")
63
- .option(
64
- "--dataset <name-or-id>",
65
- "Dataset to train on: fills the empty cells of its split column (a new split column, 80/10/10, when it has none) and freezes a slice named after the Training; pass --dataset or --slice",
66
- )
67
- .option("--slice <id>", "ready Dataset Slice that freezes a split column; pass --dataset or --slice")
68
- .option("--split-column <name-or-id>", "split column to train with, when the dataset has more than one")
69
- .option("--parts <names>", "train parts to learn on, comma-separated (default: every part with the train role)", partNames)
70
- .option("--lora-rank <rank>", "SFT LoRA adapter rank: 8, 16, or 32 (default 16)", trainingLoraRank)
71
- .option(
72
- "--gist-tokens <count>",
73
- 'gisting soft tokens: 8, 32, or 64, or a fraction of the prompt "1/4", "1/8", "1/16", "1/32" (default "1/8")',
74
- trainingGistTokens,
75
- )
76
- .option("--epochs <count>", "training epochs, 1 through 5 (default 3)", trainingEpochs)
77
- .option(
78
- "--learning-rate <rate>",
79
- "optimizer learning rate (default 0.00015 for SFT, 0.03 for gisting)",
80
- trainingLearningRate,
81
- )
82
- .option(
83
- "--batch-size <count>",
84
- "sequences per optimizer step: 8, 16, 32, or 64 (default 8)",
85
- trainingBatchSize,
86
- )
87
- .option(
88
- "--max-sequence-length <tokens>",
89
- "token budget per example, 64 through 16384 (default 12288 for SFT, 3072 for gisting)",
90
- trainingMaxSequenceLength,
91
- )
92
- .option("--prompt-file <path>", "required for gisting: non-empty UTF-8 prompt text file, at most 256 KiB")
93
- .option("--json", "print JSON", false)
94
- .description("create a Training draft")
95
- .action(async (name: string, options: RawTrainingDraftOptions & { json: boolean }) => {
96
- const { sourceRoot, client, projectId } = await resolveContext(globals(), context);
97
- assertProjectSelected(projectId);
98
- await createTraining(
99
- client,
100
- {
101
- ...trainingDraftOptions(options),
102
- sourceRoot,
103
- projectId,
104
- name,
105
- json: options.json,
106
- },
107
- context.io,
108
- );
109
- });
110
- training
111
- .command("update")
112
- .argument("<name-or-id>", "Training name or ID")
113
- .option("--base-model <id>", "catalog Base Model source", parseBaseModelId)
114
- .option("--model-version <id>", "exact Model Version source")
115
- .option(
116
- "--dataset <name-or-id>",
117
- "split the Dataset again and freeze a new slice named after the Training: rows added since get parts, rows that had one keep it",
118
- )
119
- .option("--slice <id>", "replacement ready Dataset Slice that freezes a split column")
120
- .option("--split-column <name-or-id>", "split column to train with, when the slice freezes more than one")
121
- .option("--parts <names>", "train parts to learn on, comma-separated", partNames)
122
- .option("--lora-rank <rank>", "SFT LoRA adapter rank: 8, 16, or 32", trainingLoraRank)
123
- .option(
124
- "--gist-tokens <count>",
125
- 'gisting soft tokens: 8, 32, or 64, or a fraction of the prompt "1/4", "1/8", "1/16", "1/32"',
126
- trainingGistTokens,
127
- )
128
- .option("--epochs <count>", "training epochs, 1 through 5", trainingEpochs)
129
- .option(
130
- "--learning-rate <rate>",
131
- "optimizer learning rate",
132
- trainingLearningRate,
133
- )
134
- .option(
135
- "--batch-size <count>",
136
- "sequences per optimizer step: 8, 16, 32, or 64",
137
- trainingBatchSize,
138
- )
139
- .option(
140
- "--max-sequence-length <tokens>",
141
- "token budget per example, 64 through 16384",
142
- trainingMaxSequenceLength,
143
- )
144
- .option("--prompt-file <path>", "replacement gisting prompt text file")
145
- .option("--json", "print JSON", false)
146
- .description("update a Training draft. Omitted hyperparameters keep their current values.")
147
- .action(async (nameOrId: string, options: RawTrainingDraftOptions & { json: boolean }) => {
148
- const { sourceRoot, client, projectId } = await resolveContext(globals(), context);
149
- assertProjectSelected(projectId);
150
- await updateTraining(
151
- client,
152
- {
153
- ...trainingDraftOptions(options),
154
- sourceRoot,
155
- projectId,
156
- nameOrId,
157
- json: options.json,
158
- },
159
- context.io,
160
- );
161
- });
162
- training
163
- .command("cost")
164
- .argument("<name-or-id>", "Training name or ID")
165
- .option("--idempotency-key <key>", "reuse one Cost Estimate input preparation")
166
- .option("--json", "print JSON", false)
167
- .description("validate Training inputs and calculate the maximum charge")
168
- .action(async (nameOrId: string, options: { idempotencyKey?: string; json: boolean }) => {
169
- const { client, projectId } = await resolveContext(globals(), context);
170
- assertProjectSelected(projectId);
171
- await estimateTrainingCost(
172
- client,
173
- { projectId, nameOrId, idempotencyKey: options.idempotencyKey, json: options.json },
174
- context.io,
175
- );
176
- });
177
- training
178
- .command("run")
179
- .argument("<name-or-id>", "Training name or ID")
180
- .option("--estimate-file <path>", "ready Training Cost Estimate JSON")
181
- .option("--version-name <name>", "unique Model Version name for this run")
182
- .option("--idempotency-key <key>", "reuse one Training Run creation")
183
- .option("--json", "print JSON", false)
184
- .description("calculate a ready Cost Estimate and create one queued Training Run")
185
- .action(
186
- async (
187
- nameOrId: string,
188
- options: {
189
- estimateFile?: string;
190
- versionName?: string;
191
- idempotencyKey?: string;
192
- json: boolean;
193
- },
194
- ) => {
195
- const { client, projectId } = await resolveContext(globals(), context);
196
- assertProjectSelected(projectId);
197
- await createTrainingRun(client, { projectId, nameOrId, ...options }, context.io);
198
- },
199
- );
200
- training
201
- .command("runs")
202
- .argument("<name-or-id>", "Training name or ID")
203
- .option("--json", "print JSON", false)
204
- .description("list up to 100 Training Runs (first page only)")
205
- .action(async (nameOrId: string, options: { json: boolean }) => {
206
- const { client, projectId } = await resolveContext(globals(), context);
207
- assertProjectSelected(projectId);
208
- await listTrainingRuns(client, { projectId, nameOrId, json: options.json }, context.io);
209
- });
210
- training
211
- .command("status")
212
- .argument("<training-run-id>", "Training Run ID")
213
- .option("--json", "print JSON", false)
214
- .description("show one Training Run")
215
- .action(async (trainingRunId: string, options: { json: boolean }) => {
216
- const { client } = await resolveContext(globals(), context);
217
- await getTrainingRun(client, { trainingRunId, json: options.json }, context.io);
218
- });
219
- training
220
- .command("resume")
221
- .argument("<training-run-id>", "Training Run ID")
222
- .option("--json", "print JSON", false)
223
- .description("resume a Training Run blocked on funds or payment")
224
- .action(async (trainingRunId: string, options: { json: boolean }) => {
225
- const { client } = await resolveContext(globals(), context);
226
- await resumeTrainingRun(client, { trainingRunId, json: options.json }, context.io);
227
- });
228
- training
229
- .command("cancel")
230
- .argument("<training-run-id>", "Training Run ID")
231
- .option("--json", "print JSON", false)
232
- .description("cancel a Training Run before training completes")
233
- .action(async (trainingRunId: string, options: { json: boolean }) => {
234
- const { client } = await resolveContext(globals(), context);
235
- await cancelTrainingRun(client, { trainingRunId, json: options.json }, context.io);
236
- });
237
- training
238
- .command("metrics")
239
- .argument("<training-run-id>", "Training Run ID")
240
- .option("--key <metric>", "read the point history of one metric instead of the summary")
241
- .option("--resolution <count>", "history points to return, 2 to 500 (default 200)", positiveInteger)
242
- .option("--json", "print JSON", false)
243
- .description("read Training Run metrics")
244
- .action(
245
- async (
246
- trainingRunId: string,
247
- options: { key?: string; resolution?: number; json: boolean },
248
- ) => {
249
- const { client } = await resolveContext(globals(), context);
250
- if (options.key === undefined) {
251
- await readTrainingRunMetrics(client, { trainingRunId, json: options.json }, context.io);
252
- return;
253
- }
254
- await readTrainingRunMetricHistory(
255
- client,
256
- {
257
- trainingRunId,
258
- metricKey: options.key,
259
- resolution: options.resolution,
260
- json: options.json,
261
- },
262
- context.io,
263
- );
264
- },
265
- );
266
- training
267
- .command("logs")
268
- .argument("<training-run-id>", "Training Run ID")
269
- .option("--follow", "wait for new log entries until complete", false)
270
- .description("read sanitized Training Run logs")
271
- .action(async (trainingRunId: string, options: { follow: boolean }) => {
272
- const { client } = await resolveContext(globals(), context);
273
- await readTrainingRunLogs(client, { trainingRunId, follow: options.follow }, context.io);
274
- });
275
- };
package/src/cli/models.ts DELETED
@@ -1,304 +0,0 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import { constants } from "node:fs";
3
- import { mkdir, open, realpath, rename, rm } from "node:fs/promises";
4
- import { isAbsolute, relative, resolve, sep } from "node:path";
5
- import { Readable, Transform } from "node:stream";
6
- import { pipeline } from "node:stream/promises";
7
-
8
-
9
- import type { BaseModel, BaseModelId, Model, ModelVersion, PotatoClient } from "../client";
10
- import { assertCli, REPORT_HINT, RETRY_OR_REPORT_HINT } from "./cli-error";
11
- import { formatTable, type TableIo as ModelIo, writeOutput } from "./table";
12
-
13
- type ModelApi = Pick<PotatoClient, "baseModels" | "models">;
14
-
15
- const BASE_MODEL_IDS = [
16
- "qwen3-4b",
17
- "qwen3-8b",
18
- "qwen3-32b",
19
- "qwen3-235b",
20
- ] satisfies readonly BaseModelId[];
21
-
22
- const formatBaseModel = (model: BaseModel): string =>
23
- formatTable([
24
- ["ID", model.id],
25
- ["Name", model.displayName],
26
- ["Provider", model.provider],
27
- ["Upstream model", model.upstreamModel],
28
- ["Upstream revision", model.upstreamRevision],
29
- ["Upstream snapshot", model.upstreamUrl],
30
- ]);
31
-
32
- const formatModel = (model: Model): string =>
33
- formatTable([
34
- ["ID", model.id],
35
- ["Project", model.projectId],
36
- ["Name", model.name],
37
- ["Base model", model.baseModelId],
38
- ["Description", model.description ?? "-"],
39
- ["Archived at", model.archivedAt ?? "-"],
40
- ["Created at", model.createdAt],
41
- ["Updated at", model.updatedAt],
42
- ]);
43
-
44
- export const parseBaseModelId = (value: string): BaseModelId => {
45
- const modelId = BASE_MODEL_IDS.find((candidate) => candidate === value);
46
- assertCli(
47
- modelId,
48
- `Unknown base model ${value}.`,
49
- { hint: { description: "Run toloka base-model list to see the catalog." } },
50
- );
51
- return modelId;
52
- };
53
-
54
- const resolveModel = async (
55
- client: ModelApi,
56
- projectId: string,
57
- nameOrId: string,
58
- ): Promise<Model> => {
59
- if (nameOrId.startsWith("mdl.")) return client.models.get({ projectId, modelId: nameOrId });
60
- const matches: Model[] = [];
61
- for await (const model of client.models.listAll({ projectId, limit: 100 })) {
62
- if (model.name === nameOrId) matches.push(model);
63
- }
64
- assertCli(
65
- matches.length === 1,
66
- `Model ${nameOrId} was not found or is ambiguous.`,
67
- { hint: { description: "Run toloka model list and pass the model id (mdl.…)." } },
68
- );
69
- return matches[0]!;
70
- };
71
-
72
- export const resolveModelVersion = async (
73
- client: ModelApi,
74
- projectId: string | undefined,
75
- nameOrId: string,
76
- ): Promise<ModelVersion> => {
77
- if (nameOrId.startsWith("mdv.")) return client.models.getVersion({ modelVersionId: nameOrId });
78
- const separator = nameOrId.lastIndexOf("@");
79
- assertCli(
80
- separator > 0,
81
- `Model Version ${nameOrId} was not found. Use mdv.<id> or Model@name.`,
82
- { hint: { disabled: true } },
83
- );
84
- assertCli(
85
- projectId,
86
- "Select a project to resolve Model Version names.",
87
- { hint: { description: "Select a project with toloka project add or toloka project switch, or pass the version id (mdv.…) directly." } },
88
- );
89
- const model = await resolveModel(client, projectId, nameOrId.slice(0, separator));
90
- const versionName = nameOrId.slice(separator + 1);
91
- const matches: ModelVersion[] = [];
92
- for await (const version of client.models.listAllVersions({
93
- projectId,
94
- modelId: model.id,
95
- limit: 100,
96
- })) {
97
- if (version.name === versionName) matches.push(version);
98
- }
99
- assertCli(
100
- matches.length === 1,
101
- `Model Version ${nameOrId} was not found or is ambiguous.`,
102
- { hint: { description: "Run toloka model versions <model> and pass the version id (mdv.…)." } },
103
- );
104
- return matches[0]!;
105
- };
106
-
107
- export const listBaseModels = async (
108
- client: ModelApi,
109
- input: { json: boolean },
110
- io: ModelIo,
111
- ): Promise<void> => {
112
- const models = await client.baseModels.list();
113
- writeOutput(
114
- io,
115
- input.json,
116
- models,
117
- models.length === 0
118
- ? "No base models found."
119
- : formatTable([
120
- ["ID", "NAME", "PROVIDER", "UPSTREAM MODEL", "REVISION", "UPSTREAM SNAPSHOT"],
121
- ...models.map((model) => [
122
- model.id,
123
- model.displayName,
124
- model.provider,
125
- model.upstreamModel,
126
- model.upstreamRevision.slice(0, 12),
127
- model.upstreamUrl,
128
- ]),
129
- ]),
130
- );
131
- };
132
-
133
- export const getBaseModel = async (
134
- client: ModelApi,
135
- input: { id: BaseModelId; json: boolean },
136
- io: ModelIo,
137
- ): Promise<void> => {
138
- const model = await client.baseModels.get({ id: input.id });
139
- writeOutput(io, input.json, model, formatBaseModel(model));
140
- };
141
-
142
- export const listModels = async (
143
- client: ModelApi,
144
- input: { projectId: string; json: boolean },
145
- io: ModelIo,
146
- ): Promise<void> => {
147
- const page = await client.models.listPage({ projectId: input.projectId, limit: 100, offset: 0 });
148
- writeOutput(
149
- io,
150
- input.json,
151
- page.models,
152
- page.models.length === 0
153
- ? "No models found."
154
- : formatTable([
155
- ["ID", "NAME", "BASE MODEL"],
156
- ...page.models.map((model) => [model.id, model.name, model.baseModelId]),
157
- ]),
158
- );
159
- };
160
-
161
- export const getModel = async (
162
- client: ModelApi,
163
- input: { projectId: string; nameOrId: string; json: boolean },
164
- io: ModelIo,
165
- ): Promise<void> => {
166
- const model = await resolveModel(client, input.projectId, input.nameOrId);
167
- writeOutput(io, input.json, model, formatModel(model));
168
- };
169
-
170
- export const listModelVersions = async (
171
- client: ModelApi,
172
- input: { projectId: string; nameOrId: string; json: boolean },
173
- io: ModelIo,
174
- ): Promise<void> => {
175
- const model = await resolveModel(client, input.projectId, input.nameOrId);
176
- const versions: ModelVersion[] = [];
177
- for await (const version of client.models.listAllVersions({
178
- projectId: input.projectId,
179
- modelId: model.id,
180
- limit: 100,
181
- })) {
182
- versions.push(version);
183
- }
184
- writeOutput(
185
- io,
186
- input.json,
187
- versions,
188
- versions.length === 0
189
- ? "No Model Versions found."
190
- : formatTable([
191
- ["REVISION", "NAME", "ID", "CREATED AT"],
192
- ...versions.map((version) => [
193
- String(version.revision),
194
- version.name,
195
- version.id,
196
- version.createdAt,
197
- ]),
198
- ]),
199
- );
200
- };
201
-
202
- export const createModel = async (
203
- client: ModelApi,
204
- input: {
205
- projectId: string;
206
- name: string;
207
- description?: string;
208
- baseModelId: BaseModelId;
209
- json: boolean;
210
- },
211
- io: ModelIo,
212
- ): Promise<void> => {
213
- const { json, ...body } = input;
214
- const model = await client.models.create(body);
215
- writeOutput(io, json, model, formatModel(model));
216
- };
217
-
218
- export const archiveModel = async (
219
- client: ModelApi,
220
- input: { projectId: string; nameOrId: string; json: boolean },
221
- io: ModelIo,
222
- ): Promise<void> => {
223
- const model = await resolveModel(client, input.projectId, input.nameOrId);
224
- const archived = await client.models.archive({ projectId: input.projectId, modelId: model.id });
225
- writeOutput(io, input.json, archived, `Archived Model ${archived.id}.`);
226
- };
227
-
228
- export const downloadModelVersion = async (
229
- client: ModelApi,
230
- input: { projectId?: string; modelVersionId: string; out: string },
231
- io: ModelIo,
232
- ): Promise<void> => {
233
- const version = await resolveModelVersion(client, input.projectId, input.modelVersionId);
234
- const descriptor = await client.models.getVersionContent({
235
- modelVersionId: version.id,
236
- });
237
- const root = resolve(input.out);
238
- await mkdir(root, { recursive: true });
239
- const realRoot = await realpath(root);
240
-
241
- for (const file of descriptor.files) {
242
- const target = resolve(root, file.path);
243
- const relativeTarget = relative(root, target);
244
- assertCli(
245
- relativeTarget !== "" &&
246
- relativeTarget !== ".." &&
247
- !relativeTarget.startsWith(`..${sep}`) &&
248
- !isAbsolute(relativeTarget),
249
- `Invalid Model Version file path: ${file.path}`,
250
- { hint: REPORT_HINT },
251
- );
252
- let parent = root;
253
- for (const segment of file.path.split("/").slice(0, -1)) {
254
- parent = resolve(parent, segment);
255
- await mkdir(parent, { recursive: true });
256
- const realParent = await realpath(parent);
257
- assertCli(
258
- realParent === realRoot || realParent.startsWith(`${realRoot}${sep}`),
259
- `Invalid Model Version file path: ${file.path}`,
260
- { hint: REPORT_HINT },
261
- );
262
- }
263
- const response = await fetch(file.url, { redirect: "error" });
264
- assertCli(
265
- response.ok && response.body,
266
- `Failed to download Model Version file ${file.path}.`,
267
- { hint: RETRY_OR_REPORT_HINT },
268
- );
269
- const hash = createHash("sha256");
270
- let byteSize = 0;
271
- const verify = new Transform({
272
- transform(chunk: Buffer, _encoding, callback) {
273
- byteSize += chunk.byteLength;
274
- hash.update(chunk);
275
- callback(null, chunk);
276
- },
277
- });
278
- const temporary = `${target}.${randomUUID()}.tmp`;
279
- try {
280
- const handle = await open(
281
- temporary,
282
- constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW,
283
- 0o600,
284
- );
285
- await pipeline(Readable.from(response.body), verify, handle.createWriteStream());
286
- assertCli(
287
- byteSize === file.byteSize,
288
- `Downloaded Model Version file ${file.path} has an unexpected size.`,
289
- { hint: { description: "Delete the partial download and retry; if it keeps failing, run toloka report." } },
290
- );
291
- assertCli(
292
- hash.digest("hex") === file.sha256,
293
- `Downloaded Model Version file ${file.path} has an invalid hash.`,
294
- { hint: { description: "Delete the partial download and retry; if it keeps failing, run toloka report." } },
295
- );
296
- await rename(temporary, target);
297
- } catch (error) {
298
- await rm(temporary, { force: true });
299
- throw error;
300
- }
301
- }
302
-
303
- io.stdout(`Downloaded Model Version ${descriptor.id} revision ${descriptor.revision} to ${root}`);
304
- };