@ibm-cloud/watsonx-ai
Version:
IBM watsonx.ai Node.js SDK
235 lines • 11.9 kB
JavaScript
/**
* (C) Copyright IBM Corp. 2026.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _BatchInference_apikey;
import { NoAuthAuthenticator, readExternalSources } from 'ibm-cloud-sdk-core';
import { APIBaseService } from "../base/index.mjs";
import { validateRequestParams, validateRequiredOneOf } from "../helpers/validators.mjs";
import { ENDPOINTS } from "../config/index.mjs";
import { Files } from "./files.mjs";
/**
* Helper function to validate batch inference request parameters.
*
* This function performs two levels of validation:
*
* 1. Ensures that exactly one of 'projectId' or 'spaceId' is provided (required one-of validation)
* 2. Validates that all required parameters are present and all provided parameters are valid
*
* Use this function before making batch inference API calls to ensure the request parameters meet
* the API requirements and prevent invalid requests from being sent.
*
* @example
* ```typescript
* validateBatchParams(
* { projectId: 'abc123', modelId: 'model-1' },
* ['modelId'],
* ['projectId', 'spaceId', 'modelId', 'input']
* );
* ```;
*
* @param params - The parameters object to validate (typically the request parameters)
* @param requiredParams - Array of required parameter names that must be present in params
* @param validParams - Array of all valid parameter names that are allowed in params
* @throws {Error} If validation fails - either missing required one-of fields, missing required
* params, or invalid params present
*/
function validateBatchParams(params, requiredParams, validParams) {
validateRequiredOneOf(params, ['projectId', 'spaceId'], false);
validateRequestParams(params, requiredParams, validParams);
}
/**
* Service for managing batch inference operations in watsonx.ai.
*
* Provides methods to create, retrieve, list, and cancel batch inference jobs, as well as manage
* associated files through the Files instance.
*/
export class BatchInference extends APIBaseService {
/**
* Constructs an instance of BatchInference with passed in options and external configuration.
*
* @category Constructor
* @param {UserOptions} options - The parameters to send to the service.
* @param {string} [options.apikey] - API key for authentication
* @param {string} [options.serviceName] - The name of the service to configure
* @param {string} [options.serviceUrl] - The base URL for the service
*/
constructor(options) {
options.authenticator = new NoAuthAuthenticator(); // batchInference supports different way of authentication, refer to api docs
const optionsApiKey = options.apikey;
delete options.apikey;
super(options);
_BatchInference_apikey.set(this, void 0);
const apikey = optionsApiKey !== null && optionsApiKey !== void 0 ? optionsApiKey : readExternalSources(options.serviceName).apikey;
if (!apikey)
throw new Error('API key is required.');
__classPrivateFieldSet(this, _BatchInference_apikey, apikey, "f");
this.files = new Files(this);
}
_get(params) {
return super._get(this.appendDataToHeaders(params, Object.assign({ 'authorization': `Bearer ${__classPrivateFieldGet(this, _BatchInference_apikey, "f")}` }, this._formContainerIdHeaders(params, true))));
}
_post(params) {
return super._post(this.appendDataToHeaders(params, Object.assign({ 'authorization': `Bearer ${__classPrivateFieldGet(this, _BatchInference_apikey, "f")}` }, this._formContainerIdHeaders(params, true))));
}
/**
* Create a new batch inference job.
*
* Creates a batch inference job with the specified input file, endpoint, and completion window.
* The batch job will process requests from the input file and generate results.
*
* @param {Object} params - The parameters to send to the service.
* @param {string} params.inputFileId - ID of the uploaded input file for the batch job.
* @param {string} params.endpoint - API endpoint to use for processing each batch item.
* @param {string} params.completionWindow - Time window for completion of the batch job.
* @param {string} [params.projectId] - The project that contains the resource. Either `projectId`
* or `spaceId` has to be given.
* @param {string} [params.spaceId] - The space that contains the resource. Either `spaceId` or
* `projectId` has to be given.
* @param {Record<string, string>} [params.metadata] - Additional metadata for the batch job.
* @param {OutgoingHttpHeaders} [params.headers] - Custom request headers
* @returns {Promise<Response<Batch>>} A promise that resolves to the response with batch job data
*/
create(params) {
return __awaiter(this, void 0, void 0, function* () {
const requiredParams = ['inputFileId', 'endpoint', 'completionWindow'];
const validParams = ['projectId', 'spaceId', 'metadata'];
validateBatchParams(params, requiredParams, validParams);
const { projectId, spaceId } = params;
const body = {
input_file_id: params.inputFileId,
endpoint: params.endpoint,
completion_window: params.completionWindow,
metadata: params.metadata,
};
const headers = Object.assign({}, params.headers);
const parameters = {
url: ENDPOINTS.BATCH_INFERENCE.BASE,
body,
signal: params.signal,
headers,
projectId,
spaceId,
};
return this._post(parameters);
});
}
getDetails(params) {
return __awaiter(this, void 0, void 0, function* () {
if ('batchId' in params) {
const requiredParams = ['batchId'];
const validParams = ['projectId', 'spaceId'];
validateBatchParams(params, requiredParams, validParams);
const { batchId, projectId, spaceId } = params;
const headers = Object.assign({}, params.headers);
const parameters = {
url: ENDPOINTS.BATCH_INFERENCE.BY_ID,
path: { batch_id: batchId },
signal: params.signal,
headers,
projectId,
spaceId,
};
return this._get(parameters);
}
const requiredParams = [];
const validParams = ['projectId', 'spaceId', 'limit'];
validateBatchParams(params, requiredParams, validParams);
const { limit, projectId, spaceId } = params;
const headers = Object.assign({}, params.headers);
const parameters = {
url: ENDPOINTS.BATCH_INFERENCE.BASE,
query: { limit },
signal: params.signal,
headers,
projectId,
spaceId,
};
return this._get(parameters);
});
}
/**
* List all batch jobs.
*
* Retrieves a list of all batch jobs for the specified space or project.
*
* @param {Object} params - The parameters to send to the service.
* @param {string} [params.projectId] - The project that contains the resource. Either `projectId`
* or `spaceId` has to be given.
* @param {string} [params.spaceId] - The space that contains the resource. Either `spaceId` or
* `projectId` has to be given.
* @param {number} [params.limit] - Maximum number of batch jobs to return.
* @param {OutgoingHttpHeaders} [params.headers] - Custom request headers
* @returns {Promise<Batch[]>} A promise that resolves to an array of batch jobs
*/
list(params) {
return __awaiter(this, void 0, void 0, function* () {
const response = yield this.getDetails(params);
return response.result.data;
});
}
/**
* Cancel a batch inference job.
*
* Cancels a batch inference job that is in progress. Once cancelled, the job cannot be resumed.
*
* @param {Object} params - The parameters to send to the service.
* @param {string} params.batchId - The ID of the batch job to cancel.
* @param {string} [params.projectId] - The project that contains the resource. Either `projectId`
* or `spaceId` has to be given.
* @param {string} [params.spaceId] - The space that contains the resource. Either `spaceId` or
* `projectId` has to be given.
* @param {OutgoingHttpHeaders} [params.headers] - Custom request headers
* @returns {Promise<Response<Batch>>} A promise that resolves to the response with cancelled
* batch job data
*/
cancel(params) {
return __awaiter(this, void 0, void 0, function* () {
const requiredParams = ['batchId'];
const validParams = ['projectId', 'spaceId'];
validateBatchParams(params, requiredParams, validParams);
const { batchId, projectId, spaceId } = params;
const headers = Object.assign({}, params.headers);
const parameters = {
url: ENDPOINTS.BATCH_INFERENCE.CANCEL_BY_ID,
path: { batch_id: batchId },
signal: params.signal,
headers,
projectId,
spaceId,
};
return this._post(parameters);
});
}
}
_BatchInference_apikey = new WeakMap();
//# sourceMappingURL=batch_inference.mjs.map