UNPKG

wa-chat-server

Version:

Watson Assistant powered chat server

197 lines (196 loc) 9.11 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.AssistantV2Adapter = void 0; const v2_1 = __importDefault(require("ibm-watson/assistant/v2")); const auth_1 = require("ibm-watson/auth"); const utils_1 = require("../lib/utils"); class AssistantV2Adapter { constructor(config, logger) { this.logger = logger; this.environmentId = config.environmentId; this.assistantId = config.assistantId; this.withContext = config.withContext ? config.withContext : false; this.softRestart = config.softRestart ? config.softRestart : false; } static initializeWithIamAuthenticator(config, logger) { const configForLog = Object.assign({}, config); configForLog.apikey = (0, utils_1.mask)(configForLog.apikey); logger.info(`assistant_v2: Creating IAM V2 adapter for ${config.assistantId}`, configForLog); let adapter = new AssistantV2Adapter(config, logger); adapter.assistant = new v2_1.default({ version: config.version ? config.version : '2020-04-01', authenticator: new auth_1.IamAuthenticator({ apikey: config.apikey, }), serviceUrl: config.serviceUrl, timeout: config.timeout, }); return adapter; } static initializeWithCp4dAuthenticator(config, logger) { const configForLog = Object.assign({}, config); configForLog.tokenServicePassword = (0, utils_1.mask)(configForLog.tokenServicePassword); configForLog.tokenServiceApikey = (0, utils_1.mask)(configForLog.tokenServiceApikey); logger.info(`assistant_v2: Creating CP4D V2 adapter for ${config.assistantId}`, configForLog); let adapter = new AssistantV2Adapter(config, logger); adapter.assistant = new v2_1.default({ version: config.version ? config.version : '2020-04-01', authenticator: new auth_1.CloudPakForDataAuthenticator({ username: config.tokenServiceUsername, password: config.tokenServicePassword, apikey: config.tokenServiceApikey, url: config.tokenServiceUrl, }), serviceUrl: config.serviceUrl, timeout: config.timeout, }); return adapter; } v1ContextToV2Context(context) { const contextCopy = Object.assign({}, context); const metadata = contextCopy.metadata || {}; delete contextCopy.metadata; const retVal = { // eslint-disable-next-line @typescript-eslint/camelcase skills: { ['main skill']: { user_defined: contextCopy } }, }; if (metadata.user_id) { retVal.global = { // eslint-disable-next-line @typescript-eslint/camelcase system: { user_id: metadata.user_id }, }; } return retVal; } message(payload) { return __awaiter(this, void 0, void 0, function* () { var _a; if ((_a = payload.input) === null || _a === void 0 ? void 0 : _a.text) { payload.input['message_type'] = 'text'; } payload.input.options = { debug: true }; if (this.withContext) { payload.input.options['return_context'] = true; } if (payload.input.text.toLowerCase() === 'reset') { payload.input.options.restart = true; if (!this.softRestart) { payload.input.text = ''; } } // Create session if does not exist let sessionId; if (payload.context && payload.context.sessionId && !(payload.input.options.restart && !this.softRestart)) { sessionId = payload.context.sessionId; delete payload.context.sessionId; } else { const req = { assistantId: this.assistantId }; const startTimeMS = new Date().getTime(); try { const res = yield this.assistant.createSession(req); this.logger.info(`assistant_v2.createSession():`, { request: req, response: res, durationMS: `${new Date().getTime() - startTimeMS}`, }); sessionId = res.result.session_id; } catch (e) { this.logger.error(`assistant_v2.createSession():`, { request: req, error: e, durationMS: `${new Date().getTime() - startTimeMS}`, }); throw e; } } let res; const params = { environmentId: this.environmentId, assistantId: this.assistantId || undefined, sessionId: sessionId, input: payload.input, context: this.withContext ? this.v1ContextToV2Context(payload.context) : undefined, }; let startTimeMS = new Date().getTime(); try { res = yield this.assistant.message(params); this.logger.info(`assistant_v2.message():`, { params, response: res, durationMS: `${new Date().getTime() - startTimeMS}`, }); } catch (e) { if (e.message == 'Invalid Session') { this.logger.warn(`assistant_v2.message() failed - invalid session:`, { params, error: e, durationMS: `${new Date().getTime() - startTimeMS}`, }); sessionId = (yield this.assistant.createSession({ assistantId: this.assistantId })).result .session_id; const params2 = { environmentId: this.environmentId, assistantId: this.assistantId || undefined, sessionId: sessionId, input: payload.input, context: this.withContext ? { skills: { ['main skill']: { ['user_defined']: payload.context } } } : undefined, }; startTimeMS = new Date().getTime(); try { res = yield this.assistant.message(params2); this.logger.info(`assistant_v2.message():`, { request: params2, response: res, durationMS: `${new Date().getTime() - startTimeMS}`, }); } catch (e2) { this.logger.error(`assistant_v2.message() failed:`, { request: params, error: e2, durationMS: `${new Date().getTime() - startTimeMS}`, }); throw e2; } } else { throw e; } } let v1output = res.result.output; if (v1output.user_defined) { v1output = Object.assign(Object.assign({}, v1output), v1output.user_defined); delete v1output.user_defined; } const newPayload = { headers: res.headers, status: res.status, statusText: res.statusText, result: Object.assign(Object.assign({}, res.result), { output: v1output, input: payload.input, context: Object.assign(Object.assign({}, (this.withContext ? res.result.context.skills['main skill'].user_defined : {})), { sessionId }) }), }; this.logger.info(`assistant_v2.message(); response transformed to V1 format:`, newPayload); this.sessionId = sessionId; return newPayload; }); } } exports.AssistantV2Adapter = AssistantV2Adapter;