| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- const fetch = require("node-fetch");
- class BankBot {
- static TAG = "BankBot";
- constructor() {
- this.stateMap = new Map();
- }
- async process(message, metalog) {
- console.log(`[${BankBot.TAG}] ${metalog} process:`, message);
- try {
- const { success, data } = await this.flow(message, metalog);
- return { success, data };
- } catch (e) {
- console.error(`[${BankBot.TAG}] Error:`, e);
- }
- return { success: false, data: null };
- }
- async flow(message, metalog) {
- let text = message.body.trim();
- if (!text.includes("@bsb")) return false;
- text = text.replace("@bsb", "").trim();
- let url = "https://nexilis.io/ibotbank_wsgi/predict";
- let reqJsonObject = { prompt: text };
- const session = this.stateMap.get(message.to);
- if (session) {
- console.log(`[${BankBot.TAG}] ${metalog} session:`, session);
- if (session.state === "PREDICT") {
- const parameters = session.data.parameters || {};
- if (parameters.confirmation === "1") {
- url = url.replace("predict", "auth");
- session.state = "AUTH";
- }
- } else if (session.state === "AUTH") {
- url = url.replace("predict", "execute");
- const { data } = session;
- delete data.content;
- delete data.explanation;
- delete data.confidence;
- delete data.role;
- data.message = session.prompt;
- reqJsonObject = data;
- session.state = "EXECUTE";
- }
- }
- console.log(`[${BankBot.TAG}] ${metalog} POST [${url}] ->`, reqJsonObject);
- let body;
- try {
- const res = await fetch(url, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(reqJsonObject)
- });
- body = await res.text();
- } catch (err) {
- console.error("HTTP Error:", err);
- body = JSON.stringify({
- role: "assistant",
- content: "Server Busy.. please try again later."
- });
- }
- console.log(`[${BankBot.TAG}] ${metalog} response body:`, body);
- let resJson;
- try {
- resJson = JSON.parse(body);
- } catch (e) {
- resJson = {
- role: "assistant",
- content: "Invalid JSON from server."
- };
- }
- if (resJson.parameters) {
- this.stateMap.set(
- message.to,
- new Session(text, "PREDICT", resJson)
- );
- }
- return { success: true, data: resJson };
- }
- }
- class Session {
- constructor(prompt, state, data) {
- this.prompt = prompt;
- this.state = state;
- this.data = data;
- }
- toString() {
- return `Session{prompt='${this.prompt}', state=${this.state}, data=${JSON.stringify(this.data)}}`;
- }
- }
- const State = {
- PREDICT: "PREDICT",
- AUTH: "AUTH",
- EXECUTE: "EXECUTE"
- };
- module.exports.BankBot = BankBot;
|