UNPKG

@ibm-cloud/watsonx-ai

Version:
305 lines 14 kB
"use strict"; /** * (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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; 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 __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Files = void 0; const fs_1 = __importStar(require("fs")); const promises_1 = require("fs/promises"); const stream_1 = require("stream"); const form_data_1 = __importDefault(require("form-data")); const validators_1 = require("../helpers/validators.js"); const config_1 = require("../config/index.js"); /** * Helper function to validate file operation 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 file API calls to ensure the request parameters meet the API * requirements and prevent invalid requests from being sent. * * @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 validateFilesParams(params, requiredParams, validParams) { (0, validators_1.validateRequiredOneOf)(params, ['projectId', 'spaceId'], false); (0, validators_1.validateRequestParams)(params, requiredParams, validParams); } /** * Class for managing files used in batch inference operations. * * Provides methods to upload, retrieve, list, download, and manage files associated with batch * inference jobs. */ class Files { /** * Creates an instance of Files. * * @param {BatchInference} client - The BatchInference client instance. */ constructor(client) { this.client = client; } /** * Upload a file for batch inference. * * Uploads a JSONL file containing batch requests. The file will be used as input for batch * inference jobs. * * @param {UploadBatchFileParams} params - The parameters to send to the service. * @param {string | ReadableStream | Blob} params.file - JSONL file containing batch requests. * @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<UploadedFile>>} A promise that resolves to the response with * uploaded file data */ upload(params) { return __awaiter(this, void 0, void 0, function* () { validateFilesParams(params, ['file'], ['projectId', 'spaceId']); const { file, projectId, spaceId, signal } = params; // Validate file parameter if (typeof file === 'string') { try { yield (0, promises_1.access)(file, fs_1.constants.R_OK); } catch (_a) { throw new Error(`File path does not exist or is not readable: ${file}`); } } const form = new form_data_1.default(); if (typeof file === 'string') { form.append('file', fs_1.default.createReadStream(file)); } else if (file instanceof ReadableStream) { const nodeStream = stream_1.Readable.fromWeb(file); form.append('file', nodeStream); } else { form.append('file', file); } form.append('purpose', 'batch'); const headers = Object.assign(Object.assign({}, form.getHeaders()), params.headers); const parameters = { url: config_1.ENDPOINTS.FILES.BASE, headers, signal, body: form, projectId, spaceId, }; return this.client._post(parameters); }); } getDetails(params) { return __awaiter(this, void 0, void 0, function* () { if (params && 'fileId' in params) { validateFilesParams(params, ['fileId'], ['projectId', 'spaceId']); const { fileId, projectId, spaceId } = params; const parameters = { url: config_1.ENDPOINTS.FILES.BY_ID, headers: params.headers, signal: params.signal, path: { 'file_id': fileId }, projectId, spaceId, }; return this.client._get(parameters); } validateFilesParams(params, [], ['projectId', 'spaceId', 'after', 'limit', 'purpose', 'order']); const { projectId, spaceId, after, limit, purpose = 'batch', order, signal } = params; const headers = Object.assign({ Accept: 'application/json' }, params.headers); const query = { after, limit, purpose, order }; const parameters = { url: config_1.ENDPOINTS.FILES.BASE, headers, signal, query, projectId, spaceId, }; return this.client._get(parameters); }); } /** * Retrieve file content. * * Retrieves the content of a specific file by its ID. * * @param {GetFileContentParams} params - The parameters to send to the service. * @param {string} params.fileId - The ID of the file to retrieve. * @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<string>>} A promise that resolves to the response with file content */ getContent(params) { return __awaiter(this, void 0, void 0, function* () { validateFilesParams(params, ['fileId'], ['projectId', 'spaceId']); const { fileId, projectId, spaceId } = params; const parameters = { url: config_1.ENDPOINTS.FILES.CONTENT_BY_ID, headers: params.headers, signal: params.signal, path: { 'file_id': fileId }, projectId, spaceId, }; return this.client._get(parameters); }); } /** * Check if a file exists at the specified path. * * @private * @param {string} path - The file path to check. * @returns {Promise<boolean>} A promise that resolves to true if the file exists, false otherwise */ fileExists(path) { return __awaiter(this, void 0, void 0, function* () { try { yield (0, promises_1.access)(path, fs_1.constants.F_OK); return true; } catch (_a) { return false; } }); } /** * Download file content to local filesystem. * * Downloads the content of a file and saves it to the local filesystem. The file must be in JSONL * format. * * @param {DownloadFileContentParams} params - The parameters to send to the service. * @param {string} params.filename - Name of the file to save. Must end with `.jsonl`. * @param {string} [params.path] - Directory path where the file should be saved. * @param {string} [params.fileId] - The ID of the file to download. * @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<string>} A promise that resolves to a success message with the file path * @throws {Error} If the file already exists or if the filename doesn't end with `.jsonl` */ download(params) { return __awaiter(this, void 0, void 0, function* () { validateFilesParams(params, ['filename'], ['projectId', 'spaceId', 'fileId', 'path']); const { filename, path } = params, rest = __rest(params, ["filename", "path"]); if (!filename.endsWith('.jsonl')) throw new Error('Downloaded files must be in jsonl format'); const filenameWithPath = path ? `${path}/${filename}` : filename; const fileExistsError = new Error(`File already exists: ${filenameWithPath}`); if (yield this.fileExists(filenameWithPath)) throw fileExistsError; const response = yield this.getContent(rest); const content = response.result; try { yield (0, promises_1.writeFile)(filenameWithPath, content, { flag: 'wx' }); } catch (err) { if (err.code === 'EEXIST') { throw fileExistsError; } throw err; } return `File written successfully to ${filenameWithPath}`; }); } /** * List all files. * * Retrieves a list of all files for the specified space or project. * * @param {ListFilesParams} 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 {string} [params.after] - A cursor for pagination. Use the last file ID from the * previous response to retrieve the next page. * @param {number} [params.limit] - Maximum number of files to return. Must be between 1 and * 10,000. * @param {string} [params.purpose] - Filter files by purpose. * @param {string} [params.order] - Order of results. Options are "asc" or "desc". * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers * @returns {Promise<UploadedFile[]>} A promise that resolves to an array of files */ list(params) { return __awaiter(this, void 0, void 0, function* () { validateFilesParams(params, [], ['projectId', 'spaceId', 'after', 'limit', 'purpose', 'order']); const response = yield this.getDetails(params); return response.result.data; }); } } exports.Files = Files; //# sourceMappingURL=files.js.map