-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.ts
780 lines (713 loc) · 24 KB
/
model.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
import {
DeleteModelVersionRequest,
GetModelRequest,
ListModelTypesRequest,
ListModelVersionsRequest,
MultiModelVersionResponse,
MultiOutputResponse,
PostModelOutputsRequest,
PostModelVersionsRequest,
} from "clarifai-nodejs-grpc/proto/clarifai/api/service_pb";
import { UserError } from "../errors";
import { ClarifaiUrl, ClarifaiUrlHelper } from "../urls/helper";
import { BackoffIterator, promisifyGrpcCall } from "../utils/misc";
import { AuthConfig } from "../utils/types";
import { Lister } from "./lister";
import {
Model as GrpcModel,
Input as GrpcInput,
ModelVersion,
OutputConfig,
OutputInfo,
UserAppIDSet,
} from "clarifai-nodejs-grpc/proto/clarifai/api/resources_pb";
import { StatusCode } from "clarifai-nodejs-grpc/proto/clarifai/api/status/status_code_pb";
import {
MAX_MODEL_PREDICT_INPUTS,
TRAINABLE_MODEL_TYPES,
} from "../constants/model";
import {
findAndReplaceKey,
responseToModelParams,
responseToParamInfo,
responseToTemplates,
} from "../utils/modelTrain";
import * as fs from "fs";
import * as yaml from "js-yaml";
import { Input } from "./input";
import {
JavaScriptValue,
Struct,
} from "google-protobuf/google/protobuf/struct_pb";
interface BaseModelConfig {
modelVersion?: { id: string };
modelUserAppId?: {
userId: string;
appId: string;
};
}
interface ModelConfigWithUrl extends BaseModelConfig {
url: ClarifaiUrl;
modelId?: undefined;
authConfig?: Omit<AuthConfig, "userId" | "appId">;
}
interface ModelConfigWithModelId extends BaseModelConfig {
url?: undefined;
modelId: string;
authConfig?: AuthConfig;
}
type ModelConfig = ModelConfigWithUrl | ModelConfigWithModelId;
/**
* Model is a class that provides access to Clarifai API endpoints related to Model information.
* @noInheritDoc
*/
export class Model extends Lister {
private appId: string;
private id: string;
private modelUserAppId: UserAppIDSet | undefined;
private modelVersion: { id: string } | undefined;
public modelInfo: GrpcModel;
private trainingParams: Record<string, unknown>;
/**
* Initializes a Model object.
*
* @param url - The URL to initialize the model object.
* @param modelId - The Model ID to interact with.
* @param modelVersion - The Model Version to interact with.
* @param authConfig - Authentication configuration options.
* @param authConfig.baseURL - Base API URL. Default is "https://api.clarifai.com".
* @param authConfig.pat - A personal access token for authentication. Can be set as env var CLARIFAI_PAT.
* @param authConfig.token - A session token for authentication. Accepts either a session token or a pat. Can be set as env var CLARIFAI_SESSION_TOKEN.
*
* @includeExample examples/model/index.ts
*/
constructor({
url,
modelId,
modelVersion,
authConfig = {},
modelUserAppId,
}: ModelConfig) {
if (url && modelId) {
throw new UserError("You can only specify one of url or model_id.");
}
if (!url && !modelId) {
throw new UserError("You must specify one of url or model_id.");
}
let modelIdFromUrl;
let authConfigFromUrl: AuthConfig | undefined;
if (url) {
const [userId, appId, destructuredModelId, modelVersionId] =
ClarifaiUrlHelper.splitClarifaiUrl(url);
modelIdFromUrl = destructuredModelId;
if (modelVersion) {
modelVersion.id = modelVersionId;
} else {
modelVersion = { id: modelVersionId };
}
authConfigFromUrl = {
...(authConfig as Omit<AuthConfig, "userId" | "appId">),
userId,
appId,
};
}
super({ authConfig: authConfigFromUrl || (authConfig as AuthConfig) });
this.appId = authConfigFromUrl?.appId ?? (authConfig as AuthConfig)?.appId;
this.modelVersion = modelVersion;
this.id = (modelIdFromUrl || modelId) as string;
this.modelInfo = new GrpcModel();
const grpcModelVersion = new ModelVersion();
if (this.modelVersion) {
grpcModelVersion.setId(this.modelVersion.id);
}
if (this.appId) this.modelInfo.setAppId(this.appId);
if (this.id) this.modelInfo.setId(this.id);
if (this.modelVersion) this.modelInfo.setModelVersion(grpcModelVersion);
this.trainingParams = {};
if (modelUserAppId) {
this.modelUserAppId = new UserAppIDSet()
.setAppId(modelUserAppId.appId)
.setUserId(modelUserAppId.userId);
}
}
/**
* Loads the current model info.
* Usually called internally by other methods, to ensure the model info is loaded with latest data.
*/
async loadInfo() {
const getModel = promisifyGrpcCall(
this.STUB.client.getModel,
this.STUB.client,
);
const request = new GetModelRequest();
if (this.modelUserAppId) {
request.setUserAppId(this.modelUserAppId);
} else {
request.setUserAppId(this.userAppId);
}
request.setModelId(this.id);
if (this.modelVersion?.id) request.setVersionId(this.modelVersion.id);
const response = await this.grpcRequest(getModel, request);
const responseObject = response.toObject();
if (responseObject.status?.code !== StatusCode.SUCCESS) {
throw new Error(
`Failed to get model: ${responseObject.status} : ${responseObject.status?.description}`,
);
}
this.modelInfo = new GrpcModel();
if (responseObject.model?.id) {
this.modelInfo.setId(responseObject.model?.id);
}
if (responseObject.model?.appId) {
this.modelInfo.setAppId(responseObject.model?.id);
}
const grpcModelVersion = new ModelVersion();
if (responseObject.model?.modelVersion?.id) {
grpcModelVersion.setId(responseObject.model?.modelVersion?.id);
}
this.modelInfo.setModelVersion(grpcModelVersion);
}
/**
* Lists all the training templates for the model type.
* @returns - A promise that resolves to a list of training templates for the model type.
*
* @includeExample examples/model/listTrainingTemplates.ts
*/
async listTrainingTemplates(): Promise<string[]> {
if (!this.modelInfo.getModelTypeId()) {
await this.loadInfo();
}
if (!TRAINABLE_MODEL_TYPES.includes(this.modelInfo.getModelTypeId())) {
throw new Error(
`Model type ${this.modelInfo.getModelTypeId()} is not trainable`,
);
}
const request = new ListModelTypesRequest();
if (this.modelUserAppId) {
request.setUserAppId(this.modelUserAppId);
} else {
request.setUserAppId(this.userAppId);
}
const listModelTypes = promisifyGrpcCall(
this.STUB.client.listModelTypes,
this.STUB.client,
);
const response = await this.grpcRequest(listModelTypes, request);
const responseObject = response.toObject();
if (responseObject.status?.code !== StatusCode.SUCCESS) {
throw new Error(responseObject.status?.toString());
}
const templates = responseToTemplates(
responseObject,
this.modelInfo.getModelTypeId(),
);
return templates;
}
/**
* Returns the model params for the model type as object & also writes to a yaml file
* @param template - The training template to use for the model type.
* @param saveTo - The file path to save the yaml file.
* @returns - A promise that resolves to the model params for the model type.
*
* @includeExample examples/model/getParams.ts
*/
async getParams(
template: string | null = null,
saveTo: string = "params.yaml",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<Record<string, any>> {
if (!this.modelInfo.getModelTypeId()) {
await this.loadInfo();
}
if (!TRAINABLE_MODEL_TYPES.includes(this.modelInfo.getModelTypeId())) {
throw new Error(
`Model type ${this.modelInfo.getModelTypeId()} is not trainable`,
);
}
if (
template === null &&
!["clusterer", "embedding-classifier"].includes(
this.modelInfo.getModelTypeId(),
)
) {
throw new Error(
`Template should be provided for ${this.modelInfo.getModelTypeId()} model type`,
);
}
if (
template !== null &&
["clusterer", "embedding-classifier"].includes(
this.modelInfo.getModelTypeId(),
)
) {
throw new Error(
`Template should not be provided for ${this.modelInfo.getModelTypeId()} model type`,
);
}
const request = new ListModelTypesRequest();
if (this.modelUserAppId) {
request.setUserAppId(this.modelUserAppId);
} else {
request.setUserAppId(this.userAppId);
}
const listModelTypes = promisifyGrpcCall(
this.STUB.client.listModelTypes,
this.STUB.client,
);
const response = await this.grpcRequest(listModelTypes, request);
const responseObject = response.toObject();
if (responseObject.status?.code !== StatusCode.SUCCESS) {
throw new Error(responseObject.status?.toString());
}
const params = responseToModelParams(
responseObject,
this.modelInfo.getModelTypeId(),
template,
);
// yaml file
if (!saveTo.endsWith(".yaml")) {
throw new Error("File extension should be .yaml");
}
fs.writeFileSync(saveTo, yaml.dump(params, { noRefs: true }));
this.trainingParams = { ...this.trainingParams, ...params };
return params;
}
/**
* Updates the model params for the model.
* @param modelParams - The model params to update.
*
* @includeExample examples/model/updateParams.ts
*/
updateParams(modelParams: Record<string, unknown>): void {
if (!TRAINABLE_MODEL_TYPES.includes(this.modelInfo.getModelTypeId())) {
throw new UserError(
`Model type ${this.modelInfo.getModelTypeId()} is not trainable`,
);
}
if (Object.keys(this.trainingParams).length === 0) {
throw new UserError(
`Run 'model.getParams' to get the params for the ${this.modelInfo.getModelTypeId()} model type`,
);
}
const allKeys = [
...Object.keys(this.trainingParams),
...Object.values(this.trainingParams)
.filter((value) => typeof value === "object")
.flatMap((value) => Object.keys(value as Record<string, unknown>)),
];
if (!Object.keys(modelParams).every((key) => allKeys.includes(key))) {
throw new UserError("Invalid params");
}
for (const [key, value] of Object.entries(modelParams)) {
findAndReplaceKey(this.trainingParams, key, value);
}
}
/**
* Returns the param info for the model.
*
* @includeExample examples/model/getParamInfo.ts
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async getParamInfo(param: string): Promise<Record<string, any>> {
if (!TRAINABLE_MODEL_TYPES.includes(this.modelInfo.getModelTypeId())) {
throw new UserError(
`Model type ${this.modelInfo.getModelTypeId()} is not trainable`,
);
}
if (Object.keys(this.trainingParams).length === 0) {
throw new UserError(
`Run 'model.getParams' to get the params for the ${this.modelInfo.getModelTypeId()} model type`,
);
}
const allKeys = [
...Object.keys(this.trainingParams),
...Object.values(this.trainingParams)
.filter((value) => typeof value === "object")
.flatMap((value) => Object.keys(value as Record<string, unknown>)),
];
if (!allKeys.includes(param)) {
throw new UserError(
`Invalid param: '${param}' for model type '${this.modelInfo.getModelTypeId()}'`,
);
}
const template =
// @ts-expect-error - train_params isn't typed yet
this.trainingParams?.["train_params"]?.["template"] ?? null;
const request = new ListModelTypesRequest();
if (this.modelUserAppId) {
request.setUserAppId(this.modelUserAppId);
} else {
request.setUserAppId(this.userAppId);
}
const listModelTypes = promisifyGrpcCall(
this.STUB.client.listModelTypes,
this.STUB.client,
);
const response = await this.grpcRequest(listModelTypes, request);
const responseObject = response.toObject();
if (responseObject.status?.code !== StatusCode.SUCCESS) {
throw new Error(responseObject.status?.toString());
}
const paramInfo = responseToParamInfo(
responseObject,
this.modelInfo.getModelTypeId(),
param,
template,
);
if (!paramInfo) {
throw new Error("Failed to fetch params info");
}
return paramInfo;
}
/**
* Deletes a model version for the Model.
*
* @param versionId - The version ID to delete.
*
* @includeExample examples/model/deleteVersion.ts
*/
async deleteVersion(versionId: string): Promise<void> {
const request = new DeleteModelVersionRequest();
if (this.modelUserAppId) {
request.setUserAppId(this.modelUserAppId);
} else {
request.setUserAppId(this.userAppId);
}
request.setModelId(this.id);
request.setVersionId(versionId);
const deleteModelVersion = promisifyGrpcCall(
this.STUB.client.deleteModelVersion,
this.STUB.client,
);
const response = await this.grpcRequest(deleteModelVersion, request);
const responseObject = response.toObject();
if (responseObject.status?.code !== StatusCode.SUCCESS) {
throw new Error(responseObject.status?.toString());
}
}
/**
* Creates a model version for the Model.
*
* @includeExample examples/model/createVersion.ts
*/
async createVersion(
modelVersion: ModelVersion,
): Promise<GrpcModel.AsObject | undefined> {
if (this.modelInfo.getModelTypeId() in TRAINABLE_MODEL_TYPES) {
throw new UserError(
`${this.modelInfo.getModelTypeId()} is a trainable model type. Use 'model.train()' to train the model`,
);
}
const request = new PostModelVersionsRequest();
if (this.modelUserAppId) {
request.setUserAppId(this.modelUserAppId);
} else {
request.setUserAppId(this.userAppId);
}
request.setModelId(this.id);
request.setModelVersionsList([modelVersion]);
const postModelVersions = promisifyGrpcCall(
this.STUB.client.postModelVersions,
this.STUB.client,
);
const response = await this.grpcRequest(postModelVersions, request);
const responseObject = response.toObject();
if (responseObject.status?.code !== StatusCode.SUCCESS) {
throw new Error(responseObject.status?.description);
}
return responseObject.model;
}
/**
* Lists all the versions for the model.
*
* @includeExample examples/model/listVersions.ts
*
* @remarks
* Defaults to 16 per page if pageNo is not specified
*/
async *listVersions({
pageNo,
perPage,
}: {
pageNo?: number;
perPage?: number;
} = {}): AsyncGenerator<
MultiModelVersionResponse.AsObject["modelVersionsList"],
void,
void
> {
const request = new ListModelVersionsRequest();
if (this.modelUserAppId) {
request.setUserAppId(this.modelUserAppId);
} else {
request.setUserAppId(this.userAppId);
}
request.setModelId(this.id);
const listModelVersions = promisifyGrpcCall(
this.STUB.client.listModelVersions,
this.STUB.client,
);
const allModelVersionsInfo = this.listPagesGenerator(
listModelVersions,
request,
perPage,
pageNo,
);
for await (const modelVersionInfo of allModelVersionsInfo) {
yield modelVersionInfo.toObject().modelVersionsList;
}
}
/**
* Predicts the model based on the given inputs.
* Use the `Input` module to create the input objects.
*
* @param inputs - The inputs to predict, must be less than 128.
* @param inferenceParams - The inference params to override.
* @param outputConfig - The output config to override.
* min_value (number) - The minimum value of the prediction confidence to filter.
* max_concepts (number) - The maximum number of concepts to return.
* select_concepts (Concept[]) - The concepts to select.
* sample_ms (number) - The number of milliseconds to sample.
* @returns - A promise that resolves to the model prediction.
*
* @includeExample examples/model/predict.ts
*/
async predict({
inputs,
inferenceParams,
outputConfig,
}: {
inputs: GrpcInput[];
inferenceParams?: Record<string, JavaScriptValue>;
outputConfig?: OutputConfig;
}): Promise<MultiOutputResponse.AsObject["outputsList"]> {
if (!Array.isArray(inputs)) {
throw new Error(
"Invalid inputs, inputs must be an array of Input objects.",
);
}
if (inputs.length > MAX_MODEL_PREDICT_INPUTS) {
throw new Error(`Too many inputs. Max is ${MAX_MODEL_PREDICT_INPUTS}.`);
}
this.overrideModelVersion({ inferenceParams, outputConfig });
const requestInputs: GrpcInput[] = [];
for (const input of inputs) {
requestInputs.push(input);
}
const request = new PostModelOutputsRequest();
if (this.modelUserAppId) {
request.setUserAppId(this.modelUserAppId);
} else {
request.setUserAppId(this.userAppId);
}
request.setModelId(this.id);
if (this.modelVersion && this.modelVersion.id)
request.setVersionId(this.modelVersion.id);
request.setInputsList(requestInputs);
request.setModel(this.modelInfo);
const startTime = Date.now();
const backoffIterator = new BackoffIterator();
return new Promise<MultiOutputResponse.AsObject["outputsList"]>(
(resolve, reject) => {
const makeRequest = () => {
const postModelOutputs = promisifyGrpcCall(
this.STUB.client.postModelOutputs,
this.STUB.client,
);
this.grpcRequest(postModelOutputs, request)
.then((response) => {
const responseObject = response.toObject();
if (
responseObject.status?.code === StatusCode.MODEL_DEPLOYING &&
Date.now() - startTime < 600000
) {
console.log(
`${this.id} model is still deploying, please wait...`,
);
setTimeout(makeRequest, backoffIterator.next().value * 1000);
} else if (responseObject.status?.code !== StatusCode.SUCCESS) {
reject(
new Error(
`Model Predict failed with response ${responseObject.status?.toString()}`,
),
);
} else {
resolve(response.toObject().outputsList);
}
})
.catch((error) => {
reject(
new Error(`Model Predict failed with error: ${error.message}`),
);
});
};
makeRequest();
},
);
}
/**
* Predicts the model based on the given inputs.
* Inputs can be provided as a URL.
* @param url - The URL of the input.
* @param inputType - The type of the input. Can be "image", "text", "video", or "audio".
* @param inferenceParams - The inference params to override.
* @param outputConfig - The output config to override.
* @returns - A promise that resolves to the model prediction.
*/
predictByUrl({
url,
inputType,
inferenceParams,
outputConfig,
}: {
url: string;
inputType: "image" | "text" | "video" | "audio";
inferenceParams?: Record<string, JavaScriptValue>;
outputConfig?: OutputConfig;
}): Promise<MultiOutputResponse.AsObject["outputsList"]> {
let inputProto: GrpcInput;
if (inputType === "image") {
inputProto = Input.getInputFromUrl({ inputId: "", imageUrl: url });
} else if (inputType === "text") {
inputProto = Input.getInputFromUrl({ inputId: "", textUrl: url });
} else if (inputType === "video") {
inputProto = Input.getInputFromUrl({ inputId: "", videoUrl: url });
} else if (inputType === "audio") {
inputProto = Input.getInputFromUrl({ inputId: "", audioUrl: url });
} else {
throw new Error(
`Got input type ${inputType} but expected one of image, text, video, audio.`,
);
}
return this.predict({
inputs: [inputProto],
inferenceParams,
outputConfig,
});
}
/**
* Predicts the model based on the given inputs.
* Inputs can be provided as a filepath which can be read.
* @param filepath - The filepath of the input.
* @param inputType - The type of the input. Can be "image", "text", "video", or "audio".
* @param inferenceParams - The inference params to override.
* @param outputConfig - The output config to override.
* @returns - A promise that resolves to the model prediction.
*/
predictByFilepath({
filepath,
inputType,
inferenceParams,
outputConfig,
}: {
filepath: string;
inputType: "image" | "text" | "video" | "audio";
inferenceParams?: Record<string, JavaScriptValue>;
outputConfig?: OutputConfig;
}): Promise<MultiOutputResponse.AsObject["outputsList"]> {
if (!fs.existsSync(filepath)) {
throw new Error("Invalid filepath.");
}
const fileBuffer = fs.readFileSync(filepath);
return this.predictByBytes({
inputBytes: fileBuffer,
inputType,
inferenceParams,
outputConfig,
});
}
/**
* Predicts the model based on the given inputs.
* Inputs can be provided as a Buffer.
* @param inputBytes - Input as a buffer.
* @param inputType - The type of the input. Can be "image", "text", "video", or "audio".
* @param inferenceParams - The inference params to override.
* @param outputConfig - The output config to override.
* @returns - A promise that resolves to the model prediction.
*/
predictByBytes({
inputBytes,
inputType,
inferenceParams,
outputConfig,
}: {
inputBytes: Buffer;
inputType: "image" | "text" | "video" | "audio";
inferenceParams?: Record<string, JavaScriptValue>;
outputConfig?: OutputConfig;
}): Promise<MultiOutputResponse.AsObject["outputsList"]> {
if (!(inputBytes instanceof Buffer)) {
throw new Error("Invalid bytes.");
}
let inputProto: GrpcInput;
if (inputType === "image") {
inputProto = Input.getInputFromBytes({
inputId: "",
imageBytes: inputBytes,
});
} else if (inputType === "text") {
inputProto = Input.getInputFromBytes({
inputId: "",
textBytes: inputBytes,
});
} else if (inputType === "video") {
inputProto = Input.getInputFromBytes({
inputId: "",
videoBytes: inputBytes,
});
} else if (inputType === "audio") {
inputProto = Input.getInputFromBytes({
inputId: "",
audioBytes: inputBytes,
});
} else {
throw new Error(
`Got input type ${inputType} but expected one of image, text, video, audio.`,
);
}
return this.predict({
inputs: [inputProto],
inferenceParams,
outputConfig,
});
}
/**
* Overrides the model version.
*
* @param inferenceParams - The inference params to override.
* @param outputConfig - The output config to override.
* min_value (number) - The minimum value of the prediction confidence to filter.
* max_concepts (number) - The maximum number of concepts to return.
* select_concepts (Concept[]) - The concepts to select.
* sample_ms (number) - The number of milliseconds to sample.
*/
private overrideModelVersion({
inferenceParams,
outputConfig,
}: {
inferenceParams?: Record<string, JavaScriptValue>;
outputConfig?: OutputConfig;
}): void {
let currentModelVersion = this.modelInfo.getModelVersion();
if (!currentModelVersion) {
currentModelVersion = new ModelVersion();
}
let currentOutputInfo = currentModelVersion?.getOutputInfo();
if (!currentOutputInfo) {
currentOutputInfo = new OutputInfo();
}
if (outputConfig) {
const newOutputInfo = currentOutputInfo.setOutputConfig(outputConfig);
currentModelVersion?.setOutputInfo(newOutputInfo);
this.modelInfo.setModelVersion(currentModelVersion);
}
const updatedModelVersion = this.modelInfo.getModelVersion();
const updatedOutputInfo = updatedModelVersion?.getOutputInfo();
if (updatedOutputInfo && inferenceParams) {
const params = Struct.fromJavaScript(inferenceParams);
updatedOutputInfo.setParams(params);
updatedModelVersion?.setOutputInfo(updatedOutputInfo);
this.modelInfo.setModelVersion(updatedModelVersion);
}
}
}