UNPKG

promptdesk

Version:
209 lines (208 loc) 9.37 kB
"use strict"; 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 __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PromptDesk = void 0; const axios_1 = __importDefault(require("axios")); const utils_1 = require("./utils"); class PromptDesk { constructor(obj) { this.cache = {}; this.cachedCall = (0, utils_1.memoize)((payload, headers) => __awaiter(this, void 0, void 0, function* () { return yield axios_1.default.post(`${this.serviceUrl}/api/generate`, payload, { headers }); })); this.apiKey = obj.apiKey || process.env.PROMPTDESK_API_KEY || ''; this.serviceUrl = obj.serviceUrl || process.env.PROMPTDESK_SERVICE_URL || ''; //remove trailing slash this.serviceUrl = this.serviceUrl.replace(/\/$/, ''); } ping() { var _a, _b; return __awaiter(this, void 0, void 0, function* () { try { const headers = { 'Authorization': `Bearer ${this.apiKey}`, }; const response = yield axios_1.default.get(`${this.serviceUrl}/api/ping`, { headers }); if (response.status === 200) { return response.data; } else { // Log and throw error for non-200 status codes that Axios doesn't automatically reject throw new Error(`FAILED: ${response.status}, data: ${JSON.stringify(response.data)}`); } } catch (error) { if (error.response) { // Here we handle errors that Axios caught, which includes a response (e.g., server errors like 500) throw new Error(`${error.response.status}, data: ${error.response.data.message}`); } else if (error.request) { // The request was made but no response was received throw new Error(`PromptDesk service not found.`); } else { // Something happened in setting up the request that triggered an Error throw new Error(`Error setting up the request: ${((_b = (_a = error.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.error) || error.message}`); } } }); } convertToObject(string) { // Check if input is already an object or an array if (typeof string === 'object') { return string; } // Unescape HTML entities string = this.unescapeHtml(string); // Trim whitespace string = string.trim(); const regex = /('(?=(,\s*')))|('(?=:))|((?<=([:,]\s*))')|((?<={)')|('(?=}))/g; string = string.replace(regex, '"'); try { // Try parsing as JSON return JSON.parse(string); } catch (e) { // If JSON parsing fails, return null return null; } } unescapeHtml(string) { const map = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#039;': "'", '&apos;': "'" }; return string.replace(/&amp;|&lt;|&gt;|&quot;|&#039;|&apos;/g, function (m) { return map[m]; }); } list() { return __awaiter(this, void 0, void 0, function* () { try { const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.apiKey}`, }; const response = yield axios_1.default.get(`${this.serviceUrl}/api/prompts`, { headers }); if (response.status === 200) { return response.data; } else { throw new Error(`Failed: ${response.status} ${response.statusText}`); } } catch (error) { throw new Error(`Request failed: ${error}`); } }); } generate(promptName, variables = {}, options) { var _a, _b; return __awaiter(this, void 0, void 0, function* () { if (!this.apiKey) { throw new Error("API_KEY is not set"); } const chain = options === null || options === void 0 ? void 0 : options.chain; const object = options === null || options === void 0 ? void 0 : options.object; const cache = options === null || options === void 0 ? void 0 : options.cache; let classification = options === null || options === void 0 ? void 0 : options.classification; const payload = { prompt_name: promptName, variables: variables, }; if (chain) { payload['chain'] = { uuid: chain.uuid, name: chain.name, }; } const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.apiKey}`, }; try { let response; if (cache) { payload['cache'] = true; response = yield this.cachedCall(JSON.stringify(payload), headers); } else { response = yield axios_1.default.post(`${this.serviceUrl}/api/generate`, payload, { headers }); } if (response.status !== 200) { // Log and throw error for non-200 status codes that Axios doesn't automatically reject throw new Error(`FAILED: ${response.status}, data: ${JSON.stringify(response.data)}`); } const message = response.data.message; let generatedString; if (typeof message === 'string') { generatedString = message; } else if ('content' in message) { generatedString = message.content; } else { throw new Error("Failed to generate output - content or message not found in response."); } if (object) { return this.convertToObject(generatedString); } const defaultClassification = { true: ["yes", "true", "1"], false: ["no", "false", "0"], }; if (classification) { if (classification === true) { classification = defaultClassification; } for (const key in classification) { for (const value of classification[key]) { if (generatedString.trim().toLowerCase().includes(value)) { //check if key is a boolean if (key.toLocaleLowerCase() === "true") { return true; } else if (key.toLocaleLowerCase() === "false") { return false; } else { return key; } } } } return null; } return generatedString; } catch (error) { if (error.response) { // Here we handle errors that Axios caught, which includes a response (e.g., server errors like 500) throw new Error(`${error.response.status}, data: ${error.response.data.message}`); } else if (error.request) { // The request was made but no response was received throw new Error(`PromptDesk service not found.`); } else { // Something happened in setting up the request that triggered an Error throw new Error(`Error setting up the request: ${((_b = (_a = error.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.error) || error.message}`); } } }); } } exports.PromptDesk = PromptDesk;