@toloka-platform/sdk 0.20.0 → 0.21.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.
@@ -0,0 +1,313 @@
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import { dirname } from "node:path";
3
+
4
+ import type { PotatoClient, Review, ReviewSummary } from "../client";
5
+ import { PotatoApiError } from "../errors";
6
+ import { TolokaCliError } from "./cli-error";
7
+ import { formatTable, type TableIo, writeOutput } from "./table";
8
+
9
+ type ReviewApi = Pick<PotatoClient, "reviews">;
10
+
11
+ export type ReviewListView = "awaiting" | "checking" | "closed";
12
+
13
+ const CUSTOMER_REVIEW_NOT_ENABLED_MESSAGE = "The \"customerReview\" feature is not enabled for this team";
14
+
15
+ const MAX_CRITERIA_SHOWN = 20;
16
+ const MAX_TEXT_CHARS = 1_000;
17
+ const MAX_TASK_CONTENT_CHARS = 8_000;
18
+
19
+ const characters = (count: number): string => `${count.toLocaleString("en-US")} characters`;
20
+
21
+ export const REVIEW_CUT_VIEW_HELP = [
22
+ "",
23
+ "The output is cut:",
24
+ ` at most ${MAX_CRITERIA_SHOWN} quality criteria, and at most ${MAX_CRITERIA_SHOWN} criteria in each decision;`,
25
+ ` at most ${characters(MAX_TEXT_CHARS)} of each text: criterion descriptions, comments, LLM QA check reasons;`,
26
+ ` at most ${characters(MAX_TASK_CONTENT_CHARS)} of task content, which --json prints as JSON text in taskContentJson.`,
27
+ "With --json, truncated is null when nothing was cut, and otherwise has:",
28
+ " taskContentCharacters full length of the task content when it was cut, otherwise null",
29
+ " truncatedQualityCriterionCount how many quality criteria were left out",
30
+ " truncatedVerdictCriteria { field, truncatedCount } for each decision whose criteria were cut",
31
+ " cutTexts { field, characters } for each cut text, with its full length",
32
+ " hint the --out command that saves the full review",
33
+ "review accept and review reject print the review after the decision in the same cut view.",
34
+ ].join("\n");
35
+
36
+ const boundedReview = (review: Review) => {
37
+ const cutTexts: { field: string; characters: number }[] = [];
38
+ const cut = (field: string, text: string): string => {
39
+ if (text.length <= MAX_TEXT_CHARS) return text;
40
+ cutTexts.push({ field, characters: text.length });
41
+ return `${text.slice(0, MAX_TEXT_CHARS)}… (${characters(text.length - MAX_TEXT_CHARS)} more)`;
42
+ };
43
+ const { taskContent, qualityCriteria, verdicts, ...fields } = review;
44
+ const shownCriteria = qualityCriteria.slice(0, MAX_CRITERIA_SHOWN).map((criterion, index) => ({
45
+ ...criterion,
46
+ qualityElement: cut(`qualityCriteria[${index}].qualityElement`, criterion.qualityElement),
47
+ pass: cut(`qualityCriteria[${index}].pass`, criterion.pass),
48
+ fail: cut(`qualityCriteria[${index}].fail`, criterion.fail),
49
+ }));
50
+ const shownVerdicts = verdicts.map((verdict, index) => ({
51
+ ...verdict,
52
+ criteria: verdict.criteria.slice(0, MAX_CRITERIA_SHOWN),
53
+ comment: cut(`verdicts[${index}].comment`, verdict.comment),
54
+ llmQaCheck:
55
+ verdict.llmQaCheck === null
56
+ ? null
57
+ : { ...verdict.llmQaCheck, reason: cut(`verdicts[${index}].llmQaCheck.reason`, verdict.llmQaCheck.reason) },
58
+ }));
59
+ const taskContentJson = JSON.stringify(taskContent, null, 2);
60
+ const taskContentCut = taskContentJson.length > MAX_TASK_CONTENT_CHARS;
61
+ const truncatedQualityCriterionCount = qualityCriteria.length - shownCriteria.length;
62
+ const truncatedVerdictCriteria = verdicts.flatMap(({ criteria }, index) =>
63
+ criteria.length > MAX_CRITERIA_SHOWN
64
+ ? [{ field: `verdicts[${index}].criteria`, truncatedCount: criteria.length - MAX_CRITERIA_SHOWN }]
65
+ : [],
66
+ );
67
+
68
+ return {
69
+ ...fields,
70
+ qualityCriteria: shownCriteria,
71
+ verdicts: shownVerdicts,
72
+ taskContentJson: taskContentCut ? taskContentJson.slice(0, MAX_TASK_CONTENT_CHARS) : taskContentJson,
73
+ truncated:
74
+ taskContentCut || truncatedQualityCriterionCount > 0 || truncatedVerdictCriteria.length > 0 || cutTexts.length > 0
75
+ ? {
76
+ taskContentCharacters: taskContentCut ? taskContentJson.length : null,
77
+ truncatedQualityCriterionCount,
78
+ truncatedVerdictCriteria,
79
+ cutTexts,
80
+ hint: `Run toloka review get ${review.id} --out <file> to save the full review as JSON.`,
81
+ }
82
+ : null,
83
+ };
84
+ };
85
+
86
+ type BoundedReview = ReturnType<typeof boundedReview>;
87
+
88
+ const serverMessage = (error: PotatoApiError): string =>
89
+ typeof error.body === "string" && error.body.length > 0 ? error.body : error.message;
90
+
91
+ const reviewConflictHint = (reviewId: string): string =>
92
+ `Run toloka review get ${reviewId} to see its status and how many checked rejects are left, then decide again.`;
93
+
94
+ const withReviewErrors = async <T>(conflictHint: string | undefined, request: () => Promise<T>): Promise<T> => {
95
+ try {
96
+ return await request();
97
+ } catch (error) {
98
+ if (error instanceof PotatoApiError && error.status === 403 && serverMessage(error).includes(CUSTOMER_REVIEW_NOT_ENABLED_MESSAGE)) {
99
+ throw new TolokaCliError("Customer review is not enabled for this team.", {
100
+ cause: error,
101
+ hint: { description: "Customer review is not available for this team. Choose another QA mode." },
102
+ });
103
+ }
104
+ if (error instanceof PotatoApiError && error.status === 409 && conflictHint !== undefined) {
105
+ throw new TolokaCliError(serverMessage(error), { cause: error, hint: { description: conflictHint } });
106
+ }
107
+ throw error;
108
+ }
109
+ };
110
+
111
+ const summaryRow = (review: ReviewSummary): readonly string[] => [
112
+ review.id,
113
+ review.itemId,
114
+ `${review.nodeName} (${review.nodeId})`,
115
+ review.status,
116
+ review.closedAt ?? review.deadlineAt,
117
+ ];
118
+
119
+ export const listReviews = async (
120
+ client: ReviewApi,
121
+ input: {
122
+ readonly runId: string;
123
+ readonly status: ReviewListView;
124
+ readonly nodeId?: string;
125
+ readonly limit: number;
126
+ readonly offset: number;
127
+ readonly json: boolean;
128
+ },
129
+ io: TableIo,
130
+ ): Promise<void> => {
131
+ const page = await withReviewErrors(undefined, () =>
132
+ client.reviews.listPage({
133
+ runId: input.runId,
134
+ status: input.status,
135
+ limit: input.limit,
136
+ offset: input.offset,
137
+ ...(input.nodeId === undefined ? {} : { nodeId: input.nodeId }),
138
+ }),
139
+ );
140
+ const { total, offset } = page.pagination;
141
+ const footer =
142
+ page.reviews.length === 0
143
+ ? `No ${input.status} reviews (total ${total}).`
144
+ : `Showing ${offset + 1}-${offset + page.reviews.length} of ${total}.`;
145
+
146
+ writeOutput(
147
+ io,
148
+ input.json,
149
+ page,
150
+ page.reviews.length === 0
151
+ ? footer
152
+ : [
153
+ formatTable([
154
+ ["ID", "ITEM", "NODE", "STATUS", input.status === "closed" ? "CLOSED" : "DEADLINE"],
155
+ ...page.reviews.map(summaryRow),
156
+ ]),
157
+ "",
158
+ footer,
159
+ ].join("\n"),
160
+ );
161
+ };
162
+
163
+ const formatReview = (review: BoundedReview): string => {
164
+ const taskContentCharacters = review.truncated?.taskContentCharacters ?? null;
165
+ const omittedVerdictCriteria = new Map(
166
+ (review.truncated?.truncatedVerdictCriteria ?? []).map(({ field, truncatedCount }) => [field, truncatedCount]),
167
+ );
168
+
169
+ return [
170
+ `Review: ${review.id}`,
171
+ `Status: ${review.status}`,
172
+ `Node: ${review.nodeName} (${review.nodeId})`,
173
+ `Item: ${review.itemId}`,
174
+ `Performer: ${review.performer.type}${review.performer.expertId === null ? "" : ` ${review.performer.expertId}`}`,
175
+ `Deadline: ${review.deadlineAt}`,
176
+ ...(review.closedAt === null ? [] : [`Closed: ${review.closedAt}`]),
177
+ `Checked rejects left: ${review.checkedRejectsLeft}`,
178
+ "",
179
+ "Quality criteria:",
180
+ ...review.qualityCriteria.map(
181
+ (criterion) => ` ${criterion.id} ${criterion.qualityElement}: fails when ${criterion.fail}`,
182
+ ),
183
+ ...(review.truncated !== null && review.truncated.truncatedQualityCriterionCount > 0
184
+ ? [` ${review.truncated.truncatedQualityCriterionCount} more quality criteria not shown`]
185
+ : []),
186
+ "",
187
+ "Decisions:",
188
+ ...(review.verdicts.length === 0
189
+ ? [" (none)"]
190
+ : review.verdicts.map((verdict, index) => {
191
+ const omittedCriteria = omittedVerdictCriteria.get(`verdicts[${index}].criteria`);
192
+
193
+ return [
194
+ ` ${verdict.createdAt} ${verdict.decision}${verdict.forced ? " (forced)" : ""} via ${verdict.source}`,
195
+ ...(verdict.decision === "reject"
196
+ ? [
197
+ ` criteria: ${verdict.criteria.join(", ")}${omittedCriteria === undefined ? "" : ` and ${omittedCriteria} more`}`,
198
+ ` comment: ${verdict.comment}`,
199
+ ]
200
+ : []),
201
+ ...(verdict.llmQaCheck === null
202
+ ? []
203
+ : [` LLM QA check: ${verdict.llmQaCheck.verdict}: ${verdict.llmQaCheck.reason}`]),
204
+ ].join("\n");
205
+ })),
206
+ "",
207
+ "Task content:",
208
+ review.taskContentJson,
209
+ ...(taskContentCharacters === null
210
+ ? []
211
+ : [
212
+ `…task content truncated: showing ${MAX_TASK_CONTENT_CHARS.toLocaleString("en-US")} of ${characters(taskContentCharacters)}`,
213
+ ]),
214
+ ...(review.truncated === null ? [] : ["", review.truncated.hint]),
215
+ ].join("\n");
216
+ };
217
+
218
+ export const showReview = async (
219
+ client: ReviewApi,
220
+ input: { readonly reviewId: string; readonly json: boolean; readonly outPath?: string },
221
+ io: TableIo,
222
+ ): Promise<void> => {
223
+ const review = await withReviewErrors(reviewConflictHint(input.reviewId), () => client.reviews.get({ reviewId: input.reviewId }));
224
+
225
+ if (input.outPath === undefined) {
226
+ const bounded = boundedReview(review);
227
+ writeOutput(io, input.json, bounded, formatReview(bounded));
228
+ return;
229
+ }
230
+
231
+ await mkdir(dirname(input.outPath), { recursive: true });
232
+ await writeFile(input.outPath, `${JSON.stringify(review, null, 2)}\n`);
233
+ writeOutput(
234
+ io,
235
+ input.json,
236
+ { reviewId: review.id, path: input.outPath },
237
+ `Wrote review ${review.id} to ${input.outPath}.`,
238
+ );
239
+ };
240
+
241
+ const outcomeLine = (review: Review): string => {
242
+ switch (review.status) {
243
+ case "accepted":
244
+ return `Accepted ${review.id}: the expert is paid and the task is billed.`;
245
+ case "rejected":
246
+ return `Rejected ${review.id}: the item fails at ${review.nodeName} and nothing is billed for the task.`;
247
+ case "checking":
248
+ return `Sent the reject of ${review.id} to the LLM QA check. Run toloka review get ${review.id} later to see its answer.`;
249
+ case "needs_review":
250
+ return `Review ${review.id} still needs a decision.`;
251
+ case "returned":
252
+ return `Review ${review.id} is back for a new decision: the LLM QA check did not confirm the last reject.`;
253
+ case "expired":
254
+ return `Review ${review.id} expired: its deadline passed while it was open, so the task was accepted automatically.`;
255
+ }
256
+ };
257
+
258
+ export const acceptReview = async (
259
+ client: ReviewApi,
260
+ input: { readonly reviewId: string; readonly json: boolean },
261
+ io: TableIo,
262
+ ): Promise<void> => {
263
+ const review = await withReviewErrors(reviewConflictHint(input.reviewId), () => client.reviews.accept({ reviewId: input.reviewId }));
264
+
265
+ writeOutput(io, input.json, boundedReview(review), outcomeLine(review));
266
+ };
267
+
268
+ export const acceptAwaitingReviews = async (
269
+ client: ReviewApi,
270
+ input: { readonly runId: string; readonly nodeId?: string; readonly expectedCount: number; readonly json: boolean },
271
+ io: TableIo,
272
+ ): Promise<void> => {
273
+ const listCommand = `toloka review list --run ${input.runId}${input.nodeId === undefined ? "" : ` --node ${input.nodeId}`}`;
274
+ const queued = await withReviewErrors(
275
+ `Run ${listCommand} to see the reviews that await a decision now, confirm their number with the user, and retry with --expected <number>.`,
276
+ () =>
277
+ client.reviews.acceptAwaiting({
278
+ runId: input.runId,
279
+ expectedCount: input.expectedCount,
280
+ ...(input.nodeId === undefined ? {} : { nodeId: input.nodeId }),
281
+ }),
282
+ );
283
+
284
+ writeOutput(
285
+ io,
286
+ input.json,
287
+ queued,
288
+ `Accepting ${queued.count} ${queued.count === 1 ? "review" : "reviews"} in the background. Run ${listCommand} to follow: accepted reviews leave the awaiting list.`,
289
+ );
290
+ };
291
+
292
+ export const rejectReview = async (
293
+ client: ReviewApi,
294
+ input: {
295
+ readonly reviewId: string;
296
+ readonly criteria: readonly string[];
297
+ readonly comment: string;
298
+ readonly force: boolean;
299
+ readonly json: boolean;
300
+ },
301
+ io: TableIo,
302
+ ): Promise<void> => {
303
+ const review = await withReviewErrors(reviewConflictHint(input.reviewId), () =>
304
+ client.reviews.reject({
305
+ reviewId: input.reviewId,
306
+ criteria: [...input.criteria],
307
+ comment: input.comment,
308
+ ...(input.force ? { force: true } : {}),
309
+ }),
310
+ );
311
+
312
+ writeOutput(io, input.json, boundedReview(review), outcomeLine(review));
313
+ };
package/src/client.ts CHANGED
@@ -2,6 +2,7 @@ import { assert } from "es-toolkit";
2
2
 
3
3
  import * as wire from "../openapi/gen/api";
4
4
  import type {
5
+ AcceptReviewsBody,
5
6
  AddDatasetItemsBody,
6
7
  AddExpertBanListExpertsBody,
7
8
  CreateExpertListBody,
@@ -46,6 +47,7 @@ import type {
46
47
  ListModelVersionsParams,
47
48
  ListDatasetItemsParams,
48
49
  ListPipelineRunItemsParams,
50
+ ListPipelineRunReviewsParams,
49
51
  ListPipelineRunsParams,
50
52
  ListProjectDatasetsParams,
51
53
  ListProjectPipelinesParams,
@@ -75,7 +77,10 @@ import type {
75
77
  Project as GeneratedProject,
76
78
  ProjectFile as GeneratedProjectFile,
77
79
  ProjectSecretName,
80
+ RejectReviewBody,
78
81
  ReplacePipelineGraphBody,
82
+ Review as GeneratedReview,
83
+ ReviewSummary as GeneratedReviewSummary,
79
84
  RunItem as GeneratedRunItem,
80
85
  RunJob as GeneratedRunJob,
81
86
  RunSummary as GeneratedRunSummary,
@@ -84,10 +89,11 @@ import type {
84
89
  BaseModelId as GeneratedBaseModelId,
85
90
  UpdatePipelineBody,
86
91
  UpdateProjectBody,
92
+ JsonValue as GeneratedJsonValue,
87
93
  UploadJob as GeneratedUploadJob,
88
94
  ValidatePipelineGraphBody,
89
95
  } from "../openapi/gen/api.schemas";
90
- import { listAllPages } from "./pagination";
96
+ import { listAllPages, readAllPagesFirst } from "./pagination";
91
97
  import { createRequestOptions } from "./transport";
92
98
  import type { ClientCredential } from "./transport";
93
99
  import { pollUntilTerminal, type WaitForOptions } from "./wait-for";
@@ -113,6 +119,7 @@ export type TrainingRunId = Branded<string, "TrainingRunId">;
113
119
  export type PipelineId = Branded<string, "PipelineId">;
114
120
  export type ProjectFileId = Branded<string, "ProjectFileId">;
115
121
  export type ProjectId = Branded<string, "ProjectId">;
122
+ export type ReviewId = Branded<string, "ReviewId">;
116
123
  export type RunId = Branded<string, "RunId">;
117
124
  export type RunItemId = Branded<string, "RunItemId">;
118
125
  export type UploadId = Branded<string, "UploadId">;
@@ -141,6 +148,7 @@ type ResourceIdsByProperty = {
141
148
  pipelineId: PipelineId;
142
149
  projectFileId: ProjectFileId;
143
150
  projectId: ProjectId;
151
+ reviewId: ReviewId;
144
152
  runId: RunId;
145
153
  runItemId: RunItemId;
146
154
  sliceId: DatasetSliceId;
@@ -167,7 +175,11 @@ type BrandedResource<T extends { id: string }, Id extends string> = Omit<
167
175
  id: Id;
168
176
  };
169
177
 
170
- type PublicInput<T> = T extends readonly unknown[]
178
+ type IsJsonValue<T> = [T] extends [GeneratedJsonValue] ? ([GeneratedJsonValue] extends [T] ? true : false) : false;
179
+
180
+ type PublicInput<T> = IsJsonValue<T> extends true
181
+ ? T
182
+ : T extends readonly unknown[]
171
183
  ? { [K in keyof T]: PublicInput<T[K]> }
172
184
  : T extends object
173
185
  ? {
@@ -204,6 +216,8 @@ export type BaseModelId = GeneratedBaseModelId;
204
216
  export type Pipeline = BrandedResource<GeneratedPipeline, PipelineId>;
205
217
  export type Project = BrandedResource<GeneratedProject, ProjectId>;
206
218
  export type ProjectFile = BrandedResource<GeneratedProjectFile, ProjectFileId>;
219
+ export type Review = BrandedResource<GeneratedReview, ReviewId>;
220
+ export type ReviewSummary = BrandedResource<GeneratedReviewSummary, ReviewId>;
207
221
  export type RunItem = BrandedResource<GeneratedRunItem, RunItemId>;
208
222
  export type RunJob = BrandedResource<GeneratedRunJob, RunId>;
209
223
  export type RunSummary = BrandedResource<GeneratedRunSummary, RunId>;
@@ -771,6 +785,26 @@ const createClientImplementation = (config: ClientConfig) => {
771
785
  wire.getPipelineRunItem(runId, itemId, requestOptions),
772
786
  };
773
787
 
788
+ const reviews = {
789
+ listPage: ({ runId, ...params }: { runId: RunId } & ListPipelineRunReviewsParams) =>
790
+ wire.listPipelineRunReviews(runId, params, requestOptions),
791
+ listAll: ({ runId, ...params }: { runId: RunId } & ListPipelineRunReviewsParams) =>
792
+ readAllPagesFirst(async (pageOptions) => {
793
+ const page = await wire.listPipelineRunReviews(
794
+ runId,
795
+ { ...params, ...pageOptions },
796
+ requestOptions,
797
+ );
798
+ return { items: page.reviews, pagination: page.pagination };
799
+ }, params),
800
+ get: ({ reviewId }: { reviewId: ReviewId }) => wire.getReview(reviewId, requestOptions),
801
+ accept: ({ reviewId }: { reviewId: ReviewId }) => wire.acceptReview(reviewId, requestOptions),
802
+ acceptAwaiting: ({ runId, ...body }: { runId: RunId } & AcceptReviewsBody) =>
803
+ wire.acceptPipelineRunReviews(runId, body, requestOptions),
804
+ reject: ({ reviewId, ...body }: { reviewId: ReviewId } & RejectReviewBody) =>
805
+ wire.rejectReview(reviewId, body, requestOptions),
806
+ };
807
+
774
808
  const secrets = {
775
809
  list: async ({ projectId }: { projectId: ProjectId }) =>
776
810
  (await wire.listProjectSecrets(projectId, requestOptions)).secrets,
@@ -872,6 +906,7 @@ const createClientImplementation = (config: ClientConfig) => {
872
906
  trainings,
873
907
  batchInference,
874
908
  runs,
909
+ reviews,
875
910
  secrets,
876
911
  files,
877
912
  checks,
@@ -882,7 +917,9 @@ const createClientImplementation = (config: ClientConfig) => {
882
917
  };
883
918
  };
884
919
 
885
- type PublicOutput<T> = T extends GeneratedCheckJob
920
+ type PublicOutput<T> = IsJsonValue<T> extends true
921
+ ? T
922
+ : T extends GeneratedCheckJob
886
923
  ? CheckJob
887
924
  : T extends GeneratedRunJob
888
925
  ? RunJob
@@ -920,6 +957,10 @@ type PublicOutput<T> = T extends GeneratedCheckJob
920
957
  ? ProjectFile
921
958
  : T extends GeneratedRunItem
922
959
  ? RunItem
960
+ : T extends GeneratedReview
961
+ ? Review
962
+ : T extends GeneratedReviewSummary
963
+ ? ReviewSummary
923
964
  : T extends GeneratedRunSummary
924
965
  ? RunSummary
925
966
  : T extends Blob
package/src/index.ts CHANGED
@@ -28,6 +28,9 @@ export type {
28
28
  ProjectFile,
29
29
  ProjectFileId,
30
30
  ProjectId,
31
+ Review,
32
+ ReviewId,
33
+ ReviewSummary,
31
34
  RunId,
32
35
  RunItem,
33
36
  RunItemId,
package/src/pagination.ts CHANGED
@@ -27,3 +27,14 @@ export async function* listAllPages<T>(
27
27
  offset = page.pagination.offset + page.pagination.limit;
28
28
  }
29
29
  }
30
+
31
+ export async function* readAllPagesFirst<T>(
32
+ fetchPage: (options: PaginationOptions) => Promise<Page<T>>,
33
+ options: PaginationOptions = {}
34
+ ): AsyncGenerator<T> {
35
+ const items: T[] = [];
36
+ for await (const item of listAllPages(fetchPage, options)) {
37
+ items.push(item);
38
+ }
39
+ yield* items;
40
+ }