|
| 1 | +import type { CallOptions, PromiseClient } from '@connectrpc/connect'; |
| 2 | +import type { FlatTensors, MLModel } from './ml-model'; |
| 3 | +import { Struct, type Options } from '../../types'; |
| 4 | +import type { RobotClient } from '../../robot'; |
| 5 | +import { |
| 6 | + InferRequest, |
| 7 | + MetadataRequest, |
| 8 | +} from '../../gen/service/mlmodel/v1/mlmodel_pb'; |
| 9 | +import { MLModelService } from '../../gen/service/mlmodel/v1/mlmodel_connect'; |
| 10 | + |
| 11 | +export class MLModelClient implements MLModel { |
| 12 | + private client: PromiseClient<typeof MLModelService>; |
| 13 | + private readonly name: string; |
| 14 | + private readonly options: Options; |
| 15 | + public callOptions: CallOptions = { headers: {} as Record<string, string> }; |
| 16 | + |
| 17 | + constructor(client: RobotClient, name: string, options: Options = {}) { |
| 18 | + this.client = client.createServiceClient(MLModelService); |
| 19 | + this.name = name; |
| 20 | + this.options = options; |
| 21 | + } |
| 22 | + |
| 23 | + async metadata(extra = {}, callOptions = this.callOptions) { |
| 24 | + const request = new MetadataRequest({ |
| 25 | + name: this.name, |
| 26 | + extra: Struct.fromJson(extra), |
| 27 | + }); |
| 28 | + |
| 29 | + this.options.requestLogger?.(request); |
| 30 | + |
| 31 | + return this.client.metadata(request, callOptions); |
| 32 | + } |
| 33 | + |
| 34 | + async infer( |
| 35 | + inputTensors: FlatTensors, |
| 36 | + extra = {}, |
| 37 | + callOptions = this.callOptions |
| 38 | + ) { |
| 39 | + const request = new InferRequest({ |
| 40 | + name: this.name, |
| 41 | + inputTensors, |
| 42 | + extra: Struct.fromJson(extra), |
| 43 | + }); |
| 44 | + |
| 45 | + this.options.requestLogger?.(request); |
| 46 | + |
| 47 | + return this.client.infer(request, callOptions); |
| 48 | + } |
| 49 | +} |
0 commit comments