@toloka-platform/sdk 0.26.2 → 0.27.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 (35) hide show
  1. package/README.md +2 -2
  2. package/dist/cli/toloka.js +180 -191
  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 +52 -756
  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 +42 -7
  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/authoring/index.ts +34 -3
  19. package/src/cli/analytics.ts +0 -31
  20. package/src/cli/context.ts +0 -109
  21. package/src/cli/init.ts +1 -1
  22. package/src/cli/program.ts +0 -6
  23. package/src/cli/project.ts +9 -1
  24. package/src/client.ts +0 -259
  25. package/src/importer.ts +88 -6
  26. package/src/index.ts +2 -2
  27. package/src/pipeline-graph-v1.contract.json +130 -101
  28. package/skills/toloka-fine-tuning/SKILL.md +0 -177
  29. package/skills/toloka-gisting/SKILL.md +0 -186
  30. package/src/cli/batch-inference.ts +0 -267
  31. package/src/cli/commands/batch-inference.ts +0 -116
  32. package/src/cli/commands/models.ts +0 -121
  33. package/src/cli/commands/training.ts +0 -275
  34. package/src/cli/models.ts +0 -304
  35. package/src/cli/trainings.ts +0 -880
@@ -1,186 +0,0 @@
1
- ---
2
- name: toloka-gisting
3
- description: Create, estimate, start, monitor, and verify a project-owned prompt-gisting Training through the Toloka CLI, which learns soft prompt tokens that stand in for a long static system prompt. Use when the user wants a compact or cheaper replacement for a fixed prompt, learned from example conversations and the prompt file.
4
- ---
5
-
6
- # Compress a prompt with gisting
7
-
8
- ## Mission
9
-
10
- Help the user learn a compact representation of their static prompt from representative example conversations while preserving the exact prompt and their model, data, quality, latency, and budget constraints. Match the work to the requested outcome: inspect an existing Training or run, prepare a draft, calculate an estimate, start an approved run, monitor it, or retrieve its output. Do not create resources or start a run merely because they appear later in this reference.
11
-
12
- For first-time setup details, read `https://platform.toloka.ai/agents/gisting.md`.
13
-
14
- ## Domain model
15
-
16
- - **Prompt gisting** learns soft prompt tokens that stand in for a static instruction prompt. Training examples should contain the dynamic inputs and desired assistant responses; do not repeat the static prompt in every user message.
17
- - A **Training** is an editable project-owned draft. A **Training Run** is one immutable, billable execution of a frozen draft, prompt, and the rows of its slice.
18
- - A run can start from a catalog **Base Model** or an exact existing **Model Version**. An explicit Model Version is the source; do not also select a Base Model.
19
- - A completed run publishes a durable Model Version. It does not prove deployment or inference readiness.
20
- - Training and validation are data roles, not file-layout rules. A **split column** puts each Dataset row in a part such as `train`, `validate` or `test`, and a **slice** freezes rows together with their split columns. A Training learns on a slice's rows in the train parts of one split column and validates on its validate parts, which may include a part that also tests. Without validation rows, the provider reserves 10% of the training rows as a holdout.
21
- - A Training needs `--dataset <dataset>` or `--slice <id>`. `--dataset` fills the empty cells of the Dataset's split column (a new `split` column, 80/10/10, when it has none) and freezes a slice named after the Training; `--slice` takes a slice frozen with `toloka dataset slice create`, which must freeze a split column. Rows without a part are never trained on. Rows that any split column puts in a test part never reach training, nor validation unless they sit in a validate + test part of the Training's own split column; the cost estimate reports any train rows they remove as `Left out as test`. `toloka dataset split <dataset>` places only rows without a part, so after adding rows, run it again and take a new slice: no test row moves into training. `toloka dataset columns <dataset>` shows the split columns and their roles.
22
-
23
- ## Working posture
24
-
25
- - Inspect the user's request and current CLI, project, Training, Dataset, prompt, and run state before changing anything. The process below is a dependency map: skip satisfied or irrelevant work and stop when the requested outcome is complete.
26
- - Honor explicit choices first. If a requested project, source, Dataset, prompt, or configuration is incompatible, explain the evidence and tradeoff before proposing a substitute.
27
- - Make routine reversible choices and briefly explain them. Ask a focused question only for material ambiguity, missing authorization or inputs, conflicting constraints, or destructive or out-of-scope changes.
28
- - If the goal is weight adaptation from labeled conversations or data labeling rather than prompt compression, explain the distinction and route to `toloka-fine-tuning` or `toloka-build`; never silently change the method.
29
-
30
- ## Safety
31
-
32
- - Never ask for an API key in chat; the user enters it through `toloka login`.
33
- - Never invent project, Dataset, Base Model, Training, Model, Model Version, prompt, price, or run IDs. Read identity and source metadata from the CLI.
34
- - Use only authorized project Datasets containing representative examples. Keep credentials and production data out of source control and agent messages.
35
- - The prompt file must be non-empty UTF-8 text no larger than 256 KiB. Preserve user-provided prompt text exactly unless they ask to edit it; when the prompt is supplied in chat, materialize that exact text instead of inventing missing intent.
36
- - Preserve train/validation separation and avoid duplicate or near-duplicate examples across roles.
37
- - Never start a Training Run before the user approves the ready estimate's exact `maximumCharge`.
38
- - Keep polling bounded. Report terminal state only when the CLI shows it, and report timeouts as still running.
39
-
40
- ## Process
41
-
42
- ### 1. Establish only the context the goal needs
43
-
44
- When the CLI, authentication, or binding is unknown, inspect it. The runtime-inclusive standalone CLI is sufficient for Training-only work; no separate Bun or Node.js installation, SDK, TypeScript, or test packages are needed:
45
-
46
- ```sh
47
- toloka --version
48
- toloka whoami
49
- toloka project current
50
- ```
51
-
52
- Reuse an authenticated, compatible workspace. For an inspection request, inspect existing resources rather than creating a project, Dataset, Training, prompt file, or run.
53
-
54
- Use the project the user explicitly requested. Otherwise keep the current binding when it is consistent with the task. If no suitable project is bound and the requested work needs one, inspect `toloka project list --limit 20`, then create a task-named project or register the exact existing project the user identified. Do not silently select an unrelated project or rebind an existing checkout; use an explicit `--project-id` or a separate source root when working against another project without changing the binding.
55
-
56
- ### 2. Inspect and assign data roles
57
-
58
- ```sh
59
- toloka dataset list
60
- toloka dataset fields <dataset-name-or-id>
61
- ```
62
-
63
- Use the user's authorized data and existing role assignments. If local JSONL files must be uploaded, put them in one Dataset for the task; `dataset upload` appends, and a split column records each row's role:
64
-
65
- ```sh
66
- toloka dataset create <dataset-name>
67
- toloka dataset upload <dataset-name> <absolute-jsonl-path>
68
- toloka dataset fields <dataset-name>
69
- ```
70
-
71
- When the user supplied separate training and validation files, give each file its role before uploading the next one: `toloka dataset split <dataset-name> --parts train:100 --json` after the training file, then `toloka dataset split <dataset-name> --parts validate:100 --json` after the validation file. Each fill places only rows without a part, so a supplied validation set never mixes into training; pass `--parts` on every such fill, because a fill without it repeats the column's last shares. For one undivided file, let the split sample it: `toloka dataset split <dataset-name> --ratios 80/10/10 [--balance-by <label-field>] --json`, or leave it to `training create --dataset`, which splits 80/10/10.
72
-
73
- CLI uploads to an otherwise undeclared Dataset store each row whole in its `uploaded` field, so the rows' own fields are not dataset fields yet. `toloka dataset fields add <dataset> <field>…` adds top-level fields of the uploaded rows as dataset fields, for filters and `--balance-by`, and copies their values from every upload. When the rows carry their own role, such as a Hugging Face `split` field, add it, then adopt it: `toloka dataset fields add <dataset> split`, then `toloka dataset split <dataset> --column split`. Roles follow the values `train`, `validation`/`validate`/`val`/`dev` and `test`, and `--parts train,dev=validate,test` maps other names. `dataset split` and `training create --dataset` refuse a split column name that is a field of the uploaded rows but not a dataset field, and print the `fields add` command.
74
-
75
- To train on a subset or reuse rows across Trainings, freeze a slice once every upload and split has finished; `--filter <field>=<value>` keeps only matching rows, and split columns are always frozen:
76
-
77
- ```sh
78
- toloka dataset slice create <dataset-name> --name "<slice-name>" --json
79
- ```
80
-
81
- Check that the examples demonstrate the desired behavior under the prompt: dynamic input in user messages, target output in the final assistant message, representative edge cases, and no prompt or answer leakage across validation. Rows with tool calls also need `tools` declaring every function they call. Each call's `arguments` must be a string holding a JSON object (it is not checked against the function's `parameters`), call ids must be unique within a turn, and the `tool` replies must answer every call before the next turn. Cost estimation rejects rows that break these rules and names the first few in its error.
82
-
83
- ### 3. Preserve the prompt and choose the source
84
-
85
- Confirm the prompt path contains non-empty UTF-8 text within 256 KiB. Use the supplied file as-is. If the user supplied prompt text in the request instead, write that exact text to a UTF-8 file. Ask only when the required prompt or its intended boundaries are genuinely missing; do not author a replacement prompt from assumptions.
86
-
87
- Explicit source choices take precedence. An existing Model Version bypasses Base Model selection.
88
-
89
- Gisting supports only `qwen3-4b` and `qwen3-8b` because it publishes full model weights. This restriction also applies to the underlying Base Model of an existing Model Version. Unsupported tiers are rejected when creating or updating a Training draft; explain the constraint rather than silently substituting a model.
90
-
91
- ```sh
92
- toloka base-model list --json
93
- toloka base-model get <base-model-id> --json
94
- toloka model list --json
95
- toloka model get <model-id> --json
96
- toloka model versions <model-id> --json
97
- ```
98
-
99
- For a Base Model, compare available evidence about prompt and language fit, prior quality, data volume, desired compression fidelity, training budget, and serving latency or deployment constraints. Model size alone is not a quality decision; a smaller model is a useful cost and latency baseline when the task permits it, not a mandatory default. Verify the selected catalog ID, upstream model, and pinned revision with `base-model get`, and consult upstream documentation or user-provided evidence for capabilities the catalog does not expose.
100
-
101
- Gisting starts either from a catalog Base Model or, to compress a prompt for a model you already fine-tuned, from that model's LoRA adapter Model Version via `--model-version` (the adapter is merged into the base and the gist tokens are trained over the fine-tuned weights). Because gisting publishes a full model, it is limited to the qwen3-4b and qwen3-8b tiers, and a `--model-version` source must be a LoRA adapter version (a full-weights version is rejected).
102
-
103
- ### 4. Reuse or create the draft
104
-
105
- Inspect before creating another Training:
106
-
107
- ```sh
108
- toloka training list --json
109
- toloka training get <training-id> --json
110
- ```
111
-
112
- When a new draft is needed, use a descriptive name and create normalized gisting configuration:
113
-
114
- ```sh
115
- toloka training create "<training-name>" \
116
- --method gisting \
117
- --prompt-file <absolute-prompt-path> \
118
- --base-model <base-model-id> \
119
- --dataset <dataset-name-or-id> \
120
- --json
121
- ```
122
-
123
- `--dataset` fills the empty cells of the Dataset's split column, freezes a slice named after the Training, and prints a line for each step; pass `--split-column <name>` when the Dataset has several split columns. To train on a slice frozen earlier, pass `--slice <slice-id>` instead. The Training learns on the column's train parts, or the ones `--parts <names>` lists, and validates on its validate parts; without validate rows, the platform holds out 10% of training rows for evaluation.
124
-
125
- Preserve requested hyperparameters. The current CLI uses `--gist-tokens` (default `1/8`), `--epochs 1..5` (default 3), `--learning-rate` within 0.001–0.3 (default 0.03), `--batch-size 8|16|32|64` (default 8), and `--max-sequence-length 64..16384` (default 3072), rather than `regime`. Use defaults when suitable. `--gist-tokens` takes an absolute count `8|32|64` or a fraction of the prompt being compressed — `1/4`, `1/8`, `1/16`, `1/32`. An absolute count fixes the soft-prompt size: 8 favors compression for simple prompts, while 64 may help when 32 loses holdout accuracy. A fraction fixes the compression ratio instead — the run resolves it to `ceil(prompt tokens / N)` and clamps it to 8..256 — so the default `1/8` suits a prompt whose length changes between drafts; go to `1/16` or `1/32` for harder compression when holdout accuracy holds. `training get` reports the fraction you set, not the count it resolved to. Choose sequence length from actual examples within the supported limit. `--lora-rank` is rejected for gisting. `training update <name-or-id>` takes the same flags except `--method`; omitted flags retain current values. A new `--slice` or `--dataset` resets `--split-column` and `--parts` unless you pass them again.
126
-
127
- Verify the saved method, exact source, prompt file, slice, split column, train parts, and configuration with `toloka training get <training-id> --json`.
128
-
129
- ### 5. Validate and estimate
130
-
131
- ```sh
132
- toloka training cost <training-id> --json > <absolute-estimate-file>
133
- ```
134
-
135
- A blocked estimate exits 1, leaves the redirected file empty, and prints `Training cannot run with these inputs:` followed by one `- <message>` line per issue on stderr. Report every issue, correct the cause, and calculate a new estimate.
136
-
137
- For a duration issue, use the reported rows, tokens, epochs, GPU count, and wall time to compare supported options. Gisting publishes full model weights, so only `qwen3-4b` and `qwen3-8b` are supported; switching to the larger 8-GPU tiers is not a valid workaround. Reducing rows can weaken coverage and reducing epochs can weaken compression quality. Do not silently change the requested model, discard data, or alter epochs merely to make the estimate pass. Explain the tradeoff, obtain direction when material, update the draft, re-estimate, and obtain approval for the new quote.
138
-
139
- For a ready estimate, report the source, prompt, slice and split column, training and validation row counts, any rows left out as test, token totals, maximum GPU seconds, `maximumCharge`, currency, and fingerprint. If the user asked only for an estimate, stop here.
140
-
141
- ### 6. Run only after explicit cost approval
142
-
143
- Ask the user to approve the exact ready `maximumCharge`. After approval, start only the requested run and pass the approved file so a new unseen quote cannot replace it:
144
-
145
- ```sh
146
- toloka training run <training-id> \
147
- --estimate-file <absolute-estimate-file> \
148
- --version-name <unique-version-name> \
149
- --json
150
- ```
151
-
152
- Both flags are optional at the CLI level. Without `--estimate-file`, `training run` calculates a fresh ready estimate; do not use that path when the user approved a saved quote. Without `--version-name`, the Model Version takes the Training name.
153
-
154
- Monitor only as far as the user requested, with bounded commands:
155
-
156
- ```sh
157
- toloka training status <training-run-id> --json
158
- toloka training logs <training-run-id>
159
- toloka training metrics <training-run-id> --json
160
- ```
161
-
162
- Metrics can appear while the run is `running` and stop updating when training ends, before the run reaches `completed`. When `available: false`, check `unavailableReason`:
163
-
164
- - `unresolved`: metrics are not available yet. Check again while the run is `running`.
165
- - `not_configured`: this run will not report metrics. Stop polling for them.
166
-
167
- Control and billing rules:
168
-
169
- - Resume only after the user confirms a billing block is resolved.
170
- - `payment_window_expired` is final: the run is `failed`, cannot resume, and was not charged, even though `billingStatus` remains `payment_required`. A replacement run needs funds and new cost approval.
171
- - Cancel only on explicit request, before output checks begin. Before training starts, cancellation is free. During training, it stops the GPU job and charges for GPU seconds used, with no Model Version. A startup cancellation may remain `stopping` until the job stops; wait rather than retrying cancel.
172
- - `provider_failed` and `provider_timeout` are platform failures: no charge, full hold returned. Reported GPU usage remains visible.
173
- - A `failed` or `canceled` run frees its estimate: the same estimate file can start one new run at the same `maximumCharge` until the estimate expires. Retry only an error with `retryable: true` (network, storage, or GPU capacity), and only after the user agrees.
174
-
175
- Do not duplicate a slow run. Progress `queued` or `pending` means it is waiting for GPUs; training starts automatically. Training may also exceed the estimated duration. The charge stays capped at the approved `maximumCharge`; successful runs still publish a Model Version.
176
-
177
- For a completed run, verify the observed output and download only when requested:
178
-
179
- ```sh
180
- toloka training get <training-id> --json
181
- toloka model get <model-id> --json
182
- toloka model versions <model-id> --json
183
- toloka model version download <model-version-id> --out <absolute-output-directory>
184
- ```
185
-
186
- The downloaded folder contains full model weights (`config.json` and `model-*.safetensors`) and tokenizer files, including supported text sidecars such as `merges.txt` and `chat_template.jinja`. Keep the files together. The learned prompt is represented by the special tokens `<|gist_0|>`, `<|gist_1|>`, and so on. A request must match training: the gist tokens first as plain text, then the conversation without the final assistant turn rendered by the tokenizer's chat template with `add_generation_prompt=True` and `enable_thinking=False`, without the original prompt. Send that string to a completions endpoint, because a chat endpoint wraps it in message markers; a system message holding only the gist tokens is the closest chat-only fallback and must be checked on validation rows. Verify serving separately with a compatible runtime; a successful download alone does not establish inference readiness.
@@ -1,267 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
-
3
- import type { BatchInferenceRun, PotatoClient } from "../client";
4
- import type { BaseModelId, CreateBatchInferenceRunBody } from "../../openapi/gen/api.schemas";
5
- import { assertCli } from "./cli-error";
6
- import { resolveFieldValueFilters } from "./filters";
7
- import { resolveModelVersion } from "./models";
8
- import { resolveSplitParts } from "./splits";
9
- import { formatTable, type TableIo as BatchInferenceIo, writeOutput } from "./table";
10
-
11
- type BatchInferenceApi = Pick<PotatoClient, "batchInference">;
12
- type BatchInferenceStartApi = Pick<
13
- PotatoClient,
14
- "batchInference" | "datasets" | "models" | "baseModels"
15
- >;
16
-
17
- const QUOTE_WAIT_MS = 10 * 60 * 1_000;
18
- const SETTLED_STATUSES: ReadonlySet<BatchInferenceRun["status"]> = new Set([
19
- "awaiting_confirmation",
20
- "blocked",
21
- "completed",
22
- "failed",
23
- "canceled",
24
- ]);
25
-
26
- const sleep = (ms: number) =>
27
- new Promise<void>((resolve) => {
28
- setTimeout(resolve, ms);
29
- });
30
-
31
- export const formatBatchInferenceRun = (run: BatchInferenceRun): string =>
32
- formatTable([
33
- ["ID", run.id],
34
- ["Status", run.status],
35
- ["Dataset", run.datasetId],
36
- ["Model", run.model.type === "base_model" ? run.model.baseModelId : run.model.modelVersionId],
37
- [
38
- "Output",
39
- run.output.type === "field"
40
- ? `field ${run.output.fieldId} on dataset ${run.output.datasetId}`
41
- : `new dataset ${run.output.datasetId}`,
42
- ],
43
- ...(run.quote
44
- ? [
45
- ["Rows", String(run.quote.requests)],
46
- ["Skipped rows", String(run.quote.skippedRows)],
47
- ["Maximum charge", `$${run.quote.maximumCharge}`],
48
- ...(run.quote.confirmBefore ? [["Confirm before", run.quote.confirmBefore]] : []),
49
- ]
50
- : []),
51
- ...(run.progress?.requests
52
- ? [["Progress", `${run.progress.requests.done}/${run.progress.requests.total} rows`]]
53
- : []),
54
- ...(run.chargedAmount ? [["Charged", `$${run.chargedAmount}`]] : []),
55
- ...(run.result
56
- ? [
57
- ["Written", String(run.result.written)],
58
- ["Failed", String(run.result.failed)],
59
- ["Cut at max tokens", String(run.result.truncated)],
60
- ["Tokens", `${run.result.inputTokens} in, ${run.result.outputTokens} out`],
61
- ]
62
- : []),
63
- ...(run.message ? [["Message", run.message]] : []),
64
- ]);
65
-
66
- const waitUntil = async (
67
- client: BatchInferenceApi,
68
- batchInferenceRunId: string,
69
- isReady: (run: BatchInferenceRun) => boolean,
70
- pollIntervalMs: number,
71
- timeoutMs: number,
72
- ): Promise<BatchInferenceRun> => {
73
- const deadline = Date.now() + timeoutMs;
74
- for (;;) {
75
- const run = await client.batchInference.getRun({ batchInferenceRunId });
76
- if (isReady(run)) return run;
77
- assertCli(Date.now() < deadline, `Batch Inference Run ${run.id} is still ${run.status}.`, {
78
- hint: { description: `Check it later with toloka batch-inference status ${run.id}.` },
79
- });
80
- await sleep(pollIntervalMs);
81
- }
82
- };
83
-
84
- export type StartBatchInferenceRunInput = {
85
- projectId: string;
86
- datasetId: string;
87
- filter?: string;
88
- slice?: string;
89
- parts?: string[];
90
- splitColumn?: string;
91
- baseModel?: BaseModelId;
92
- modelVersion?: string;
93
- outputField?: string;
94
- outputDataset?: string;
95
- maxOutputTokens: number;
96
- temperature?: number;
97
- topP?: number;
98
- stop: string[];
99
- seed?: number;
100
- samplesPerRow?: number;
101
- idempotencyKey?: string;
102
- yes: boolean;
103
- json: boolean;
104
- pollIntervalMs?: number;
105
- };
106
-
107
- const resolveItemFilter = async (
108
- client: BatchInferenceStartApi,
109
- input: StartBatchInferenceRunInput,
110
- ): Promise<CreateBatchInferenceRunBody["itemFilter"]> => {
111
- assertCli(
112
- input.splitColumn === undefined || input.parts !== undefined,
113
- "--split-column needs --parts.",
114
- { hint: { description: "Pass --parts test to answer the rows of the test part." } },
115
- );
116
- const itemFilter = {
117
- ...(input.filter !== undefined &&
118
- (await resolveFieldValueFilters(
119
- client,
120
- { datasetId: input.datasetId, name: input.datasetId, nameIsUnique: false },
121
- [input.filter],
122
- ))),
123
- ...(input.slice !== undefined && { slice: { sliceId: input.slice } }),
124
- ...(input.parts !== undefined && {
125
- parts: await resolveSplitParts(client, input.datasetId, {
126
- splitColumn: input.splitColumn,
127
- parts: input.parts,
128
- }),
129
- }),
130
- };
131
- return Object.keys(itemFilter).length > 0 ? itemFilter : undefined;
132
- };
133
-
134
- export const startBatchInferenceRun = async (
135
- client: BatchInferenceStartApi,
136
- input: StartBatchInferenceRunInput,
137
- io: BatchInferenceIo,
138
- ): Promise<void> => {
139
- assertCli(
140
- (input.baseModel === undefined) !== (input.modelVersion === undefined),
141
- "Pass exactly one of --base-model or --model-version.",
142
- {
143
- hint: {
144
- description: "Run toloka base-model list or toloka model versions <model> to pick one.",
145
- },
146
- },
147
- );
148
- assertCli(
149
- (input.outputField === undefined) !== (input.outputDataset === undefined),
150
- "Pass exactly one of --output-field or --output-dataset.",
151
- {
152
- hint: {
153
- description:
154
- "--output-field writes a column on the dataset; --output-dataset creates a new dataset with the prompts and answers.",
155
- },
156
- },
157
- );
158
- const itemFilter = await resolveItemFilter(client, input);
159
- const model: CreateBatchInferenceRunBody["model"] = input.baseModel
160
- ? { type: "base_model", baseModelId: input.baseModel }
161
- : {
162
- type: "model_version",
163
- modelVersionId: (await resolveModelVersion(client, input.projectId, input.modelVersion!))
164
- .id,
165
- };
166
- const created = await client.batchInference.createRun({
167
- projectId: input.projectId,
168
- idempotencyKey: input.idempotencyKey ?? randomUUID(),
169
- datasetId: input.datasetId,
170
- ...(itemFilter && { itemFilter }),
171
- model,
172
- sampling: {
173
- maxOutputTokens: input.maxOutputTokens,
174
- ...(input.temperature !== undefined && { temperature: input.temperature }),
175
- ...(input.topP !== undefined && { topP: input.topP }),
176
- ...(input.stop.length > 0 && { stop: input.stop }),
177
- ...(input.seed !== undefined && { seed: input.seed }),
178
- ...(input.samplesPerRow !== undefined && { samplesPerRow: input.samplesPerRow }),
179
- },
180
- output:
181
- input.outputField === undefined
182
- ? { type: "dataset", name: input.outputDataset! }
183
- : { type: "field", fieldName: input.outputField },
184
- });
185
- const quoted = await waitUntil(
186
- client,
187
- created.id,
188
- (run) => run.status !== "preparing",
189
- input.pollIntervalMs ?? 1_000,
190
- QUOTE_WAIT_MS,
191
- );
192
- assertCli(quoted.status === "awaiting_confirmation", formatBatchInferenceRun(quoted), {
193
- hint: { description: "Fix the selection or the model, then start a new run." },
194
- });
195
- if (!input.yes) {
196
- writeOutput(
197
- io,
198
- input.json,
199
- quoted,
200
- `${formatBatchInferenceRun(quoted)}\n\nConfirm the maximum charge with: toloka batch-inference confirm ${quoted.id}`,
201
- );
202
- return;
203
- }
204
- const confirmed = await client.batchInference.confirmRun({ batchInferenceRunId: quoted.id });
205
- writeOutput(io, input.json, confirmed, formatBatchInferenceRun(confirmed));
206
- };
207
-
208
- export const listBatchInferenceRuns = async (
209
- client: BatchInferenceApi,
210
- input: { projectId: string; json: boolean },
211
- io: BatchInferenceIo,
212
- ): Promise<void> => {
213
- const page = await client.batchInference.listRunsPage({
214
- projectId: input.projectId,
215
- limit: 100,
216
- offset: 0,
217
- });
218
- writeOutput(
219
- io,
220
- input.json,
221
- page.batchInferenceRuns,
222
- page.batchInferenceRuns.length === 0
223
- ? "No Batch Inference Runs found."
224
- : formatTable([
225
- ["ID", "STATUS", "DATASET", "MAXIMUM CHARGE", "CHARGED"],
226
- ...page.batchInferenceRuns.map((run) => [
227
- run.id,
228
- run.status,
229
- run.datasetId,
230
- run.quote ? `$${run.quote.maximumCharge}` : "-",
231
- run.chargedAmount ? `$${run.chargedAmount}` : "-",
232
- ]),
233
- ]),
234
- );
235
- };
236
-
237
- export const getBatchInferenceRun = async (
238
- client: BatchInferenceApi,
239
- input: { batchInferenceRunId: string; wait: boolean; json: boolean; pollIntervalMs?: number },
240
- io: BatchInferenceIo,
241
- ): Promise<void> => {
242
- const run = input.wait
243
- ? await waitUntil(
244
- client,
245
- input.batchInferenceRunId,
246
- (candidate) => SETTLED_STATUSES.has(candidate.status),
247
- input.pollIntervalMs ?? 5_000,
248
- Number.POSITIVE_INFINITY,
249
- )
250
- : await client.batchInference.getRun({ batchInferenceRunId: input.batchInferenceRunId });
251
- writeOutput(io, input.json, run, formatBatchInferenceRun(run));
252
- };
253
-
254
- export const changeBatchInferenceRun = async (
255
- client: BatchInferenceApi,
256
- input: { batchInferenceRunId: string; action: "confirm" | "cancel" | "resume"; json: boolean },
257
- io: BatchInferenceIo,
258
- ): Promise<void> => {
259
- const request = { batchInferenceRunId: input.batchInferenceRunId };
260
- const run =
261
- input.action === "confirm"
262
- ? await client.batchInference.confirmRun(request)
263
- : input.action === "cancel"
264
- ? await client.batchInference.cancelRun(request)
265
- : await client.batchInference.resumeRun(request);
266
- writeOutput(io, input.json, run, formatBatchInferenceRun(run));
267
- };
@@ -1,116 +0,0 @@
1
- import type { Command } from "commander";
2
-
3
- import {
4
- changeBatchInferenceRun,
5
- getBatchInferenceRun,
6
- listBatchInferenceRuns,
7
- startBatchInferenceRun,
8
- type StartBatchInferenceRunInput,
9
- } from "../batch-inference";
10
- import {
11
- collectValues,
12
- nonNegativeInteger,
13
- partNames,
14
- positiveInteger,
15
- resolveContext,
16
- samplingTemperature,
17
- samplingTopP,
18
- type CommandHost,
19
- } from "../context";
20
- import { parseBaseModelId } from "../models";
21
- import { assertProjectSelected } from "../project-context";
22
-
23
- type RunOptions = Omit<StartBatchInferenceRunInput, "projectId" | "datasetId"> & {
24
- dataset: string;
25
- };
26
-
27
- export const registerBatchInferenceCommands = (program: Command, host: CommandHost): void => {
28
- const { context, globals } = host;
29
- const batchInference = program
30
- .command("batch-inference")
31
- .description("answer dataset rows with a base model or Model Version");
32
- batchInference
33
- .command("run")
34
- .requiredOption("--dataset <id>", "Dataset whose chat messages are the prompts")
35
- .option("--filter <field=value>", "only rows whose field equals the value")
36
- .option("--slice <id>", "only rows of this ready Dataset Slice, with the prompts it froze")
37
- .option(
38
- "--parts <names>",
39
- "only rows in these split parts, comma-separated, for example test",
40
- partNames,
41
- )
42
- .option(
43
- "--split-column <name-or-id>",
44
- "split column that --parts names, when the dataset has more than one",
45
- )
46
- .option("--base-model <id>", "catalog Base Model that answers; pass exactly one of --base-model or --model-version", parseBaseModelId)
47
- .option("--model-version <id>", "Model Version that answers: mdv.<id> or Model@name; pass exactly one of --base-model or --model-version")
48
- .option("--output-field <name>", "text field on the dataset that receives the answers; pass exactly one of --output-field or --output-dataset")
49
- .option("--output-dataset <name>", "new dataset that receives the prompts and answers; pass exactly one of --output-field or --output-dataset")
50
- .requiredOption(
51
- "--max-output-tokens <count>",
52
- "token limit per answer, at most 8192",
53
- positiveInteger,
54
- )
55
- .option(
56
- "--temperature <value>",
57
- "sampling temperature from 0 to 2 (default 0)",
58
- samplingTemperature,
59
- )
60
- .option("--top-p <value>", "nucleus sampling threshold above 0 and at most 1", samplingTopP)
61
- .option("--stop <text>", "stop sequence; repeat for up to four", collectValues, [])
62
- .option("--seed <number>", "sampling seed", nonNegativeInteger)
63
- .option(
64
- "--samples-per-row <count>",
65
- "answers per row, at most 16; above 1 needs --output-dataset and a temperature above 0",
66
- positiveInteger,
67
- )
68
- .option("--idempotency-key <key>", "reuse the run of an earlier identical request")
69
- .option("--yes", "confirm the quoted maximum charge and start right away", false)
70
- .option("--json", "print JSON", false)
71
- .description("quote a Batch Inference Run, then confirm it to start")
72
- .action(async (options: RunOptions) => {
73
- const { client, projectId } = await resolveContext(globals(), context);
74
- assertProjectSelected(projectId);
75
- const { dataset, ...rest } = options;
76
- await startBatchInferenceRun(client, { ...rest, projectId, datasetId: dataset }, context.io);
77
- });
78
- batchInference
79
- .command("list")
80
- .option("--json", "print JSON", false)
81
- .description("list up to 100 of the selected project's Batch Inference Runs (first page only)")
82
- .action(async (options: { json: boolean }) => {
83
- const { client, projectId } = await resolveContext(globals(), context);
84
- assertProjectSelected(projectId);
85
- await listBatchInferenceRuns(client, { projectId, json: options.json }, context.io);
86
- });
87
- batchInference
88
- .command("status")
89
- .argument("<batch-inference-run-id>", "Batch Inference Run ID")
90
- .option("--wait", "wait until the run finishes or needs you", false)
91
- .option("--json", "print JSON", false)
92
- .description("show one Batch Inference Run")
93
- .action(async (batchInferenceRunId: string, options: { wait: boolean; json: boolean }) => {
94
- const { client } = await resolveContext(globals(), context);
95
- await getBatchInferenceRun(client, { batchInferenceRunId, ...options }, context.io);
96
- });
97
- for (const [action, description] of [
98
- ["confirm", "accept the quoted maximum charge and start the run"],
99
- ["resume", "resume a run blocked on funds or payment"],
100
- ["cancel", "cancel a run; answers already generated are kept and the GPU time used is charged"],
101
- ] as const) {
102
- batchInference
103
- .command(action)
104
- .argument("<batch-inference-run-id>", "Batch Inference Run ID")
105
- .option("--json", "print JSON", false)
106
- .description(description)
107
- .action(async (batchInferenceRunId: string, options: { json: boolean }) => {
108
- const { client } = await resolveContext(globals(), context);
109
- await changeBatchInferenceRun(
110
- client,
111
- { batchInferenceRunId, action, json: options.json },
112
- context.io,
113
- );
114
- });
115
- }
116
- };