@tiledesk/tiledesk-tybot-connector 2.0.9 → 2.0.10-rc10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/CHANGELOG.md +27 -2
  2. package/ExtApi.js +1 -8
  3. package/ExtUtil.js +5 -6
  4. package/Logger.js +28 -17
  5. package/engine/IntentForm.js +0 -1
  6. package/engine/IntentsMachineFactory.js +4 -4
  7. package/engine/MongodbBotsDataSource.js +0 -1
  8. package/engine/MongodbIntentsMachine.js +0 -1
  9. package/engine/TiledeskChatbot.js +11 -16
  10. package/engine/TiledeskIntentsMachine.js +1 -2
  11. package/engine/mock/MockBotsDataSource.js +1 -2
  12. package/index.js +22 -25
  13. package/logs/app.log +4727 -44700
  14. package/logs/app2.log +46280 -0
  15. package/logs/app3.log +31686 -0
  16. package/logs/app4.log +46163 -0
  17. package/logs/app5.log +39983 -0
  18. package/logs/app6.log +21337 -0
  19. package/package.json +3 -2
  20. package/services/AIService.js +1 -1
  21. package/tiledeskChatbotPlugs/DirectivesChatbotPlug.js +38 -18
  22. package/tiledeskChatbotPlugs/FillParamsChatbotPlug.js +1 -2
  23. package/tiledeskChatbotPlugs/MarkbotChatbotPlug.js +1 -3
  24. package/tiledeskChatbotPlugs/SplitsChatbotPlug.js +1 -3
  25. package/tiledeskChatbotPlugs/WebhookChatbotPlug.js +7 -9
  26. package/tiledeskChatbotPlugs/directives/DEPRECATED_DirIfNotOpenHours.js +3 -10
  27. package/tiledeskChatbotPlugs/directives/DEPRECATED_DirIfOpenHours.js +2 -9
  28. package/tiledeskChatbotPlugs/directives/DirAddKbContent.js +332 -0
  29. package/tiledeskChatbotPlugs/directives/DirAddTags.js +16 -4
  30. package/tiledeskChatbotPlugs/directives/DirAiPrompt.js +16 -0
  31. package/tiledeskChatbotPlugs/directives/DirAskGPT.js +0 -1
  32. package/tiledeskChatbotPlugs/directives/DirAskGPTV2.js +16 -0
  33. package/tiledeskChatbotPlugs/directives/DirAssign.js +5 -8
  34. package/tiledeskChatbotPlugs/directives/DirAssignFromFunction.js +1 -3
  35. package/tiledeskChatbotPlugs/directives/DirAssistant.js +0 -1
  36. package/tiledeskChatbotPlugs/directives/DirBrevo.js +4 -6
  37. package/tiledeskChatbotPlugs/directives/DirCaptureUserReply.js +0 -1
  38. package/tiledeskChatbotPlugs/directives/DirClose.js +0 -2
  39. package/tiledeskChatbotPlugs/directives/DirCode.js +0 -1
  40. package/tiledeskChatbotPlugs/directives/DirCondition.js +0 -1
  41. package/tiledeskChatbotPlugs/directives/DirConnectBlock.js +0 -1
  42. package/tiledeskChatbotPlugs/directives/DirContactUpdate.js +1 -3
  43. package/tiledeskChatbotPlugs/directives/DirCustomerio.js +0 -1
  44. package/tiledeskChatbotPlugs/directives/DirDeflectToHelpCenter.js +2 -5
  45. package/tiledeskChatbotPlugs/directives/DirDeleteVariable.js +0 -1
  46. package/tiledeskChatbotPlugs/directives/DirDepartment.js +1 -3
  47. package/tiledeskChatbotPlugs/directives/DirFireTiledeskEvent.js +1 -3
  48. package/tiledeskChatbotPlugs/directives/DirFlowLog.js +88 -0
  49. package/tiledeskChatbotPlugs/directives/DirForm.js +1 -3
  50. package/tiledeskChatbotPlugs/directives/DirGptTask.js +0 -1
  51. package/tiledeskChatbotPlugs/directives/DirGptTask_OLD.js +36 -55
  52. package/tiledeskChatbotPlugs/directives/DirHubspot.js +0 -1
  53. package/tiledeskChatbotPlugs/directives/DirIfOnlineAgents.js +1 -4
  54. package/tiledeskChatbotPlugs/directives/DirIfOnlineAgentsV2.js +1 -4
  55. package/tiledeskChatbotPlugs/directives/DirIfOpenHours.js +0 -2
  56. package/tiledeskChatbotPlugs/directives/DirIfOpenHours_OLD.js +8 -12
  57. package/tiledeskChatbotPlugs/directives/DirIntent.js +6 -5
  58. package/tiledeskChatbotPlugs/directives/DirJSONCondition.js +0 -1
  59. package/tiledeskChatbotPlugs/directives/DirLockIntent.js +0 -1
  60. package/tiledeskChatbotPlugs/directives/DirMake.js +1 -16
  61. package/tiledeskChatbotPlugs/directives/DirMessage.js +1 -3
  62. package/tiledeskChatbotPlugs/directives/DirMessageToBot.js +0 -1
  63. package/tiledeskChatbotPlugs/directives/DirMoveToAgent.js +1 -4
  64. package/tiledeskChatbotPlugs/directives/DirMoveToUnassigned.js +0 -3
  65. package/tiledeskChatbotPlugs/directives/DirQapla.js +0 -1
  66. package/tiledeskChatbotPlugs/directives/DirRandomReply.js +1 -3
  67. package/tiledeskChatbotPlugs/directives/DirRemoveCurrentBot.js +1 -2
  68. package/tiledeskChatbotPlugs/directives/DirReplaceBot.js +1 -3
  69. package/tiledeskChatbotPlugs/directives/DirReplaceBotV2.js +1 -3
  70. package/tiledeskChatbotPlugs/directives/DirReplaceBotV3.js +1 -3
  71. package/tiledeskChatbotPlugs/directives/DirReply.js +8 -19
  72. package/tiledeskChatbotPlugs/directives/DirReplyV2.js +8 -13
  73. package/tiledeskChatbotPlugs/directives/DirSendEmail.js +1 -3
  74. package/tiledeskChatbotPlugs/directives/DirSendWhatsapp.js +0 -1
  75. package/tiledeskChatbotPlugs/directives/DirSetAttribute.js +0 -1
  76. package/tiledeskChatbotPlugs/directives/DirSetAttributeV2.js +1 -4
  77. package/tiledeskChatbotPlugs/directives/DirSetConversationTags.js +1 -3
  78. package/tiledeskChatbotPlugs/directives/DirUnlockIntent.js +0 -1
  79. package/tiledeskChatbotPlugs/directives/DirWait.js +0 -1
  80. package/tiledeskChatbotPlugs/directives/DirWebRequest.js +0 -1
  81. package/tiledeskChatbotPlugs/directives/DirWebRequestV2.js +19 -19
  82. package/tiledeskChatbotPlugs/directives/DirWebResponse.js +6 -40
  83. package/tiledeskChatbotPlugs/directives/DirWhatsappByAttribute.js +0 -1
  84. package/tiledeskChatbotPlugs/directives/Directives.js +3 -0
  85. package/utils/TiledeskChatbotUtil.js +19 -57
  86. package/TdCache copy.js +0 -242
  87. package/logs/app1.log +0 -16071
  88. package/tiledeskChatbotPlugs/directives/DirWebRequestV2_old.js +0 -417
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiledesk/tiledesk-tybot-connector",
3
- "version": "2.0.9",
3
+ "version": "2.0.10-rc10",
4
4
  "description": "Tiledesk Tybot connector",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -15,7 +15,7 @@
15
15
  "@tiledesk/tiledesk-chatbot-client": "^0.5.30",
16
16
  "@tiledesk/tiledesk-chatbot-util": "^0.8.39",
17
17
  "@tiledesk/tiledesk-client": "^0.10.13",
18
- "@tiledesk/tiledesk-multi-worker": "^0.2.1-rc2",
18
+ "@tiledesk/tiledesk-multi-worker": "^0.3.1-rc12",
19
19
  "accept-language-parser": "^1.5.0",
20
20
  "app-root-path": "^3.1.0",
21
21
  "axios": "^1.7.7",
@@ -29,6 +29,7 @@
29
29
  "liquidjs": "^10.8.4",
30
30
  "minimist-string": "^1.0.2",
31
31
  "mongoose": "^6.3.5",
32
+ "mqtt": "^5.10.4",
32
33
  "multer": "^1.4.5-lts.1",
33
34
  "nanoid": "^3.1.25",
34
35
  "redis": "^4.7.0",
@@ -31,7 +31,7 @@ class AiService {
31
31
  else {
32
32
  resolve(resbody)
33
33
  }
34
- }, this.LOG
34
+ }
35
35
  );
36
36
  });
37
37
  }
@@ -57,8 +57,10 @@ const { DirReplaceBotV3 } = require('./directives/DirReplaceBotV3');
57
57
  const { DirAiTask, DirAiPrompt } = require('./directives/DirAiPrompt');
58
58
  const { DirWebResponse } = require('./directives/DirWebResponse');
59
59
  const { DirConnectBlock } = require('./directives/DirConnectBlock');
60
+ const { DirAddKbContent } = require('./directives/DirAddKbContent');
60
61
 
61
62
  const winston = require('../utils/winston');
63
+ const { DirFlowLog } = require('./directives/DirFlowLog');
62
64
 
63
65
  class DirectivesChatbotPlug {
64
66
 
@@ -73,7 +75,6 @@ class DirectivesChatbotPlug {
73
75
  this.API_ENDPOINT = config.API_ENDPOINT;
74
76
  this.TILEBOT_ENDPOINT = config.TILEBOT_ENDPOINT;
75
77
  this.token = config.token;
76
- this.log = config.log;
77
78
  this.HELP_CENTER_API_ENDPOINT = config.HELP_CENTER_API_ENDPOINT;
78
79
  this.tdcache = config.cache;
79
80
  this.directives = config.directives;
@@ -142,8 +143,7 @@ class DirectivesChatbotPlug {
142
143
  projectId: projectId,
143
144
  token: token,
144
145
  APIURL: API_ENDPOINT,
145
- APIKEY: "___",
146
- log: this.log
146
+ APIKEY: "___"
147
147
  });
148
148
  }
149
149
  catch(err) {
@@ -162,8 +162,7 @@ class DirectivesChatbotPlug {
162
162
  TILEBOT_ENDPOINT: TILEBOT_ENDPOINT,
163
163
  departmentId: depId,
164
164
  tdcache: tdcache,
165
- HELP_CENTER_API_ENDPOINT: this.HELP_CENTER_API_ENDPOINT,
166
- log: this.log
165
+ HELP_CENTER_API_ENDPOINT: this.HELP_CENTER_API_ENDPOINT
167
166
  }
168
167
  winston.debug("(DirectivesChatbotPlug) this.context.departmentId: " + this.context.departmentId);
169
168
 
@@ -177,9 +176,7 @@ class DirectivesChatbotPlug {
177
176
 
178
177
  async nextDirective(directives) {
179
178
  winston.debug("(DirectivesChatbotPlug) ....nextDirective() checkStep()");
180
- const go_on = await TiledeskChatbot.checkStep(
181
- this.context.tdcache, this.context.requestId, this.chatbot?.MAX_STEPS, this.chatbot?.MAX_EXECUTION_TIME, this.log
182
- );
179
+ const go_on = await TiledeskChatbot.checkStep(this.context.tdcache, this.context.requestId, this.chatbot?.MAX_STEPS, this.chatbot?.MAX_EXECUTION_TIME);
183
180
 
184
181
  if (go_on.error) {
185
182
  winston.debug("(DirectivesChatbotPlug) go_on == false! nextDirective() Stopped!");
@@ -222,14 +219,13 @@ class DirectivesChatbotPlug {
222
219
  directive_name = directive.name.toLowerCase();
223
220
  }
224
221
  if (directive && directive.action) {
225
- const action_id = directive.action["_tdActionId"];
226
- const locked_action_id = await this.chatbot.currentLockedAction(this.supportRequest.request_id);
227
- if ( locked_action_id && (locked_action_id !== action_id) ) {
228
- let next_dir = await this.nextDirective(this.directives);
229
- this.process(next_dir);
230
- return;
231
- }
232
-
222
+ const action_id = directive.action["_tdActionId"];
223
+ const locked_action_id = await this.chatbot.currentLockedAction(this.supportRequest.request_id);
224
+ if ( locked_action_id && (locked_action_id !== action_id) ) {
225
+ let next_dir = await this.nextDirective(this.directives);
226
+ this.process(next_dir);
227
+ return;
228
+ }
233
229
  }
234
230
  if (directive == null || (directive !== null && directive["name"] === undefined)) {
235
231
  winston.debug("(DirectivesChatbotPlug) stop process(). directive is (null?): ", directive);
@@ -701,12 +697,37 @@ class DirectivesChatbotPlug {
701
697
  }
702
698
  });
703
699
  }
700
+ else if (directive_name === Directives.WEBHOOK) {
701
+ // console.log(".....DirIntent")
702
+ new DirIntent(context).execute(directive, async (stop) => {
703
+ if (stop) {
704
+ if (context.log) { console.log("Stopping Actions on:", JSON.stringify(directive));}
705
+ this.theend();
706
+ }
707
+ else {
708
+ let next_dir = await this.nextDirective(this.directives);
709
+ this.process(next_dir);
710
+ }
711
+ });
712
+ }
704
713
  else if (directive_name === Directives.WEB_RESPONSE) {
705
714
  new DirWebResponse(context).execute(directive, async () => {
706
715
  let next_dir = await this.nextDirective(this.directives);
707
716
  this.process(next_dir);
708
717
  });
709
718
  }
719
+ else if (directive_name === Directives.FLOW_LOG) {
720
+ new DirFlowLog(context).execute(directive, async () => {
721
+ let next_dir = await this.nextDirective(this.directives);
722
+ this.process(next_dir);
723
+ })
724
+ }
725
+ else if (directive_name === Directives.ADD_KB_CONTENT) {
726
+ new DirAddKbContent(context).execute(directive, async () => {
727
+ let next_dir = await this.nextDirective(this.directives);
728
+ this.process(next_dir);
729
+ });
730
+ }
710
731
  else {
711
732
  let next_dir = await this.nextDirective(this.directives);
712
733
  this.process(next_dir);
@@ -733,8 +754,7 @@ class DirectivesChatbotPlug {
733
754
  projectId: projectId,
734
755
  token: token,
735
756
  APIURL: API_ENDPOINT,
736
- APIKEY: "___",
737
- log: false
757
+ APIKEY: "___"
738
758
  });
739
759
  let i = -1;
740
760
  winston.debug("(DirectivesChatbotPlug) processing Inline directives: ", directives);
@@ -11,8 +11,7 @@ class FillParamsChatbotPlug {
11
11
  *
12
12
  */
13
13
 
14
- constructor(request, tdcache, log) {
15
- this.log = log;
14
+ constructor(request, tdcache) {
16
15
  this.tdcache = tdcache;
17
16
  this.request = request;
18
17
  }
@@ -10,9 +10,7 @@ class MarkbotChatbotPlug {
10
10
  *
11
11
  */
12
12
 
13
- constructor(log) {
14
- this.log = log;
15
- }
13
+ constructor() {}
16
14
 
17
15
  exec(pipeline) {
18
16
  let message = pipeline.message;
@@ -10,9 +10,7 @@ class SplitsChatbotPlug {
10
10
  *
11
11
  */
12
12
 
13
- constructor(log) {
14
- this.log = log;
15
- }
13
+ constructor() {}
16
14
 
17
15
  exec(pipeline) {
18
16
  let message = pipeline.message;
@@ -3,11 +3,10 @@ const winston = require('../utils/winston');
3
3
 
4
4
  class WebhookChatbotPlug {
5
5
 
6
- constructor(supportRequest, webhookurl, token, log) {
6
+ constructor(supportRequest, webhookurl, token) {
7
7
  this.supportRequest = supportRequest;
8
8
  this.webhookurl = webhookurl;
9
9
  this.token = token;
10
- this.log = log;
11
10
  }
12
11
 
13
12
  exec(pipeline) {
@@ -101,19 +100,18 @@ class WebhookChatbotPlug {
101
100
  callback(null, res.data);
102
101
  }
103
102
  }
104
- }, this.log
105
- );
103
+ });
106
104
  }
107
105
 
108
106
  // ************************************************
109
107
  // ****************** HTTP REQUEST ****************
110
108
  // ************************************************
111
109
 
112
- static myrequest(options, callback, log) {
113
- if (log) {
110
+ static myrequest(options, callback) {
111
+
114
112
  winston.debug("(WebhookChatbotPlug) myrequest API URL:" + options.url);
115
113
  winston.debug("(WebhookChatbotPlug) myrequest Options:", options);
116
- }
114
+
117
115
  axios(
118
116
  {
119
117
  url: options.url,
@@ -122,11 +120,11 @@ class WebhookChatbotPlug {
122
120
  headers: options.headers
123
121
  })
124
122
  .then(function (res) {
125
- if (log) {
123
+
126
124
  winston.debug("(WebhookChatbotPlug) myrequest Response for url:", options.url);
127
125
  winston.debug("(WebhookChatbotPlug) myrequest Response headers:\n", res.headers);
128
126
  winston.debug("(WebhookChatbotPlug) myrequest Response body:\n", res.data);
129
- }
127
+
130
128
  if (callback) {
131
129
  callback(null, res);
132
130
  }
@@ -12,8 +12,7 @@ class DirIfNotOpenHours {
12
12
  projectId: context.projectId,
13
13
  token: context.token,
14
14
  APIURL: context.TILEDESK_APIURL,
15
- APIKEY: "___",
16
- log: context.log
15
+ APIKEY: "___"
17
16
  });
18
17
  // this.intentDir = config.intentDir;
19
18
  // let context = {
@@ -22,19 +21,16 @@ class DirIfNotOpenHours {
22
21
  // requestId: supportRequest,
23
22
  // APIURL: API_URL,
24
23
  // TILEBOT_ENDPOINT:TILEBOT_ENDPOINT,
25
- // departmentId: depId,
26
- // log: false
24
+ // departmentId: depId
27
25
  // }
28
26
  this.intentDir = new DirIntent(
29
27
  {
30
28
  API_ENDPOINT: context.TILEDESK_APIURL,
31
29
  TILEBOT_ENDPOINT: context.TILEBOT_ENDPOINT,
32
30
  supportRequest: context.supportRequest,
33
- token: context.token,
34
- log: context.log
31
+ token: context.token
35
32
  }
36
33
  );
37
- this.log = context.log;
38
34
  }
39
35
 
40
36
  execute(directive, callback) {
@@ -58,7 +54,6 @@ class DirIfNotOpenHours {
58
54
  go(action, callback) {
59
55
  const intentName = action.body.intentName;
60
56
  if (!intentName) {
61
- if (this.log) {console.log("Invalid intent name for If-open-hours");}
62
57
  callback();
63
58
  }
64
59
  let intentDirective = {
@@ -69,13 +64,11 @@ class DirIfNotOpenHours {
69
64
  }
70
65
  }
71
66
  this.tdclient.openNow((err, result) => {
72
- if (this.log) {console.log("openNow():", result);}
73
67
  if (err) {
74
68
  console.error("DirIfNotOpenHours Error:", err);
75
69
  callback();
76
70
  }
77
71
  else if (result && !result.isopen) {
78
- if (this.log) {console.log("executing the action on 'closed'");}
79
72
  this.intentDir.execute(intentDirective, () => {
80
73
  callback();
81
74
  });
@@ -12,8 +12,7 @@ class DirIfOpenHours {
12
12
  projectId: context.projectId,
13
13
  token: context.token,
14
14
  APIURL: context.TILEDESK_APIURL,
15
- APIKEY: "___",
16
- log: context.log
15
+ APIKEY: "___"
17
16
  });
18
17
  // let context = {
19
18
  // projectId: projectId,
@@ -22,7 +21,6 @@ class DirIfOpenHours {
22
21
  // APIURL: API_URL,
23
22
  // TILEBOT_ENDPOINT:TILEBOT_ENDPOINT,
24
23
  // departmentId: depId,
25
- // log: false
26
24
  // }
27
25
  this.intentDir = new DirIntent(
28
26
  {
@@ -30,10 +28,8 @@ class DirIfOpenHours {
30
28
  TILEBOT_ENDPOINT: context.TILEBOT_ENDPOINT,
31
29
  supportRequest: context.supportRequest,
32
30
  token: context.token,
33
- log: context.log
34
31
  }
35
- );
36
- this.log = context.log;
32
+ )
37
33
  }
38
34
 
39
35
  execute(directive, callback) {
@@ -56,7 +52,6 @@ class DirIfOpenHours {
56
52
  go(action, callback) {
57
53
  const intentName = action.body.intentName;
58
54
  if (!intentName) {
59
- if (this.log) {console.log("Invalid intent name for If-open-hours");}
60
55
  callback();
61
56
  }
62
57
  let intentDirective = {
@@ -67,13 +62,11 @@ class DirIfOpenHours {
67
62
  }
68
63
  }
69
64
  this.tdclient.openNow((err, result) => {
70
- if (this.log) {console.log("openNow():", result);}
71
65
  if (err) {
72
66
  console.error("DirIfOpenHours Error:", err);
73
67
  callback();
74
68
  }
75
69
  else if (result && result.isopen) {
76
- if (this.log) {console.log("executing the action on 'open'");}
77
70
  this.intentDir.execute(intentDirective, () => {
78
71
  callback();
79
72
  });
@@ -0,0 +1,332 @@
1
+ const axios = require("axios").default;
2
+ const { TiledeskChatbot } = require('../../engine/TiledeskChatbot');
3
+ const { Filler } = require('../Filler');
4
+ let https = require("https");
5
+ const { DirIntent } = require("./DirIntent");
6
+ const { TiledeskChatbotConst } = require("../../engine/TiledeskChatbotConst");
7
+ const { TiledeskChatbotUtil } = require("../../utils/TiledeskChatbotUtil");
8
+ const assert = require("assert");
9
+ require('dotenv').config();
10
+ const winston = require('../../utils/winston');
11
+ const httpUtils = require("../../utils/HttpUtils");
12
+ const integrationService = require("../../services/IntegrationService");
13
+ const { Logger } = require("../../Logger");
14
+
15
+ class DirAddKbContent {
16
+
17
+ constructor(context) {
18
+ if (!context) {
19
+ throw new Error('context object is mandatory');
20
+ }
21
+ this.context = context;
22
+ this.chatbot = context.chatbot;
23
+ this.tdcache = this.context.tdcache;
24
+ this.requestId = this.context.requestId;
25
+ this.projectId = this.context.projectId;
26
+ this.token = this.context.token;
27
+ this.intentDir = new DirIntent(context);
28
+ this.API_ENDPOINT = this.context.API_ENDPOINT;
29
+ this.log = context.log;
30
+ this.logger = new Logger({ request_id: this.requestId, dev: this.context.supportRequest.draft });
31
+ }
32
+
33
+ execute(directive, callback) {
34
+ this.logger.info("Execute AskKnowledgeBase action")
35
+ winston.debug("DirAskGPTV2 directive: ", directive);
36
+ let action;
37
+ if (directive.action) {
38
+ action = directive.action;
39
+ }
40
+ else {
41
+ this.logger.error("Incorrect action for ", directive.name, directive)
42
+ winston.debug("DirAskGPTV2 Incorrect directive: ", directive);
43
+ callback();
44
+ return;
45
+ }
46
+ this.go(action, (stop) => {
47
+ this.logger.info("Acion AskKnowledgeBase completed");
48
+ callback(stop);
49
+ })
50
+ }
51
+
52
+ async go(action, callback) {
53
+ winston.debug("[DirAddKbContent] action:", action);
54
+ if (!this.tdcache) {
55
+ winston.error("[DirAddKbContent] Error: tdcache is mandatory");
56
+ callback();
57
+ return;
58
+ }
59
+
60
+ let publicKey = false;
61
+ let type = action.type;
62
+ let name = action.name;
63
+ let content = action.content;
64
+ let engine;
65
+
66
+ // default values
67
+ let namespace = this.context.projectId;
68
+
69
+ if (action.namespace) {
70
+ namespace = action.namespace;
71
+ }
72
+
73
+ let requestVariables = null;
74
+ requestVariables =
75
+ await TiledeskChatbot.allParametersStatic(
76
+ this.tdcache, this.requestId
77
+ );
78
+
79
+ const filler = new Filler();
80
+ const filled_content = filler.fill(content, requestVariables);
81
+ const filled_name = filler.fill(name, requestVariables);
82
+
83
+ const kb_endpoint = process.env.API_ENDPOINT;
84
+ winston.verbose("[DirAddKbContent] KbEndpoint URL: " + kb_endpoint);
85
+
86
+ let key = await integrationService.getKeyFromIntegrations(this.projectId, 'openai', this.token);
87
+ if (!key) {
88
+ this.logger.debug("[DirAddKbContent] OpenAI key not found in Integration. Using shared OpenAI key");
89
+ winston.verbose("[DirAddKbContent] - Key not found in Integrations. Searching in kb settings...");
90
+ key = await this.getKeyFromKbSettings();
91
+ }
92
+
93
+ if (!key) {
94
+ winston.verbose("[DirAddKbContent] - Retrieve public gptkey")
95
+ key = process.env.GPTKEY;
96
+ publicKey = true;
97
+ } else {
98
+ this.logger.debug("[DirAddKbContent] use your own OpenAI key")
99
+ }
100
+
101
+ if (!key) {
102
+ winston.info("[DirAddKbContent] Error: gptkey is mandatory");
103
+ await this.chatbot.addParameter("flowError", "[DirAddKbContent] Error: gptkey is mandatory");
104
+ callback();
105
+ return;
106
+ }
107
+
108
+ if (publicKey === true) {
109
+ let keep_going = await this.checkQuoteAvailability();
110
+ if (keep_going === false) {
111
+ this.logger.warn("[DirAddKbContent] Tokens quota exceeded. Skip the action")
112
+ winston.verbose("[DirAddKbContent] - Quota exceeded for tokens. Skip the action")
113
+ await this.chatbot.addParameter("flowError", "[DirAddKbContent] Error: tokens quota exceeded");
114
+ callback(true);
115
+ return;
116
+ }
117
+ }
118
+
119
+ let ns;
120
+
121
+ if (action.namespaceAsName) {
122
+ // Namespace could be an attribute
123
+ const filled_namespace = filler.fill(action.namespace, requestVariables)
124
+ this.logger.debug("[DirAddKbContent] Searching namespace by name ", filled_namespace);
125
+ ns = await this.getNamespace(filled_namespace, null);
126
+ namespace = ns?.id;
127
+ winston.verbose("[DirAddKbContent] - Retrieved namespace id from name " + namespace);
128
+ } else {
129
+ this.logger.debug("[DirAddKbContent] Searching namespace by id ", namespace);
130
+ ns = await this.getNamespace(null, namespace);
131
+ }
132
+
133
+ if (!ns) {
134
+ this.logger.error("[DirAddKbContent] Namespace not found");
135
+ await this.chatbot.addParameter("flowError", "[DirAddKbContent] Error: namespace not found");
136
+ callback();
137
+ return;
138
+ }
139
+
140
+ if (ns.engine) {
141
+ engine = ns.engine;
142
+ } else {
143
+ engine = await this.setDefaultEngine()
144
+ }
145
+
146
+ if (!namespace) {
147
+ this.logger.error("[DirAddKbContent] Namespace is undefined")
148
+ winston.verbose("[DirAddKbContent] - Error: namespace is undefined")
149
+ await this.chatbot.addParameter("flowError", "[DirAddKbContent] Error: namespace is undefined");
150
+ callback(true);
151
+ return;
152
+ }
153
+
154
+ let json = {
155
+ content: filled_content,
156
+ namespace: namespace,
157
+ type: type,
158
+ name: filled_name,
159
+ source: filled_name
160
+ };
161
+
162
+ winston.debug("[DirAddKbContent] json:", json);
163
+
164
+ const HTTPREQUEST = {
165
+ url: kb_endpoint + "/" + this.projectId + "/kb",
166
+ headers: {
167
+ 'Content-Type': 'application/json',
168
+ 'Authorization': 'JWT ' + this.context.token
169
+ },
170
+ json: json,
171
+ method: "POST"
172
+ }
173
+ winston.debug("[DirAddKbContent] HttpRequest: ", HTTPREQUEST);
174
+
175
+ httpUtils.request(
176
+ HTTPREQUEST, async (err, resbody) => {
177
+
178
+ if (err) {
179
+ this.logger.error("[DirAddKbContent] error: " + JSON.stringify(err?.response));
180
+ winston.error("[DirAddKbContent] error: ", err?.response);
181
+ if (callback) {
182
+ callback();
183
+ return;
184
+ }
185
+ }
186
+ else if (resbody.success === true) {
187
+ winston.debug("[DirAddKbContent] resbody: ", resbody);
188
+ callback();
189
+ return;
190
+ } else {
191
+ callback();
192
+ return;
193
+ }
194
+ }
195
+ )
196
+ }
197
+
198
+ async getKeyFromKbSettings() {
199
+ return new Promise((resolve) => {
200
+
201
+ const KB_HTTPREQUEST = {
202
+ url: this.API_ENDPOINT + "/" + this.context.projectId + "/kbsettings",
203
+ headers: {
204
+ 'Content-Type': 'application/json',
205
+ 'Authorization': 'JWT ' + this.context.token
206
+ },
207
+ method: "GET"
208
+ }
209
+ winston.debug("DirAskGPTV2 KB HttpRequest", KB_HTTPREQUEST);
210
+
211
+ httpUtils.request(
212
+ KB_HTTPREQUEST, async (err, resbody) => {
213
+ if (err) {
214
+ winston.error("DirAskGPTV2 Get kb settings error ", err?.response?.data);
215
+ resolve(null);
216
+ } else {
217
+ if (!resbody.gptkey) {
218
+ resolve(null);
219
+ } else {
220
+ resolve(resbody.gptkey);
221
+ }
222
+ }
223
+ }
224
+ )
225
+ })
226
+ }
227
+
228
+ async checkQuoteAvailability() {
229
+ return new Promise((resolve) => {
230
+
231
+ const HTTPREQUEST = {
232
+ url: this.API_ENDPOINT + "/" + this.context.projectId + "/quotes/tokens",
233
+ headers: {
234
+ 'Content-Type': 'application/json',
235
+ 'Authorization': 'JWT ' + this.context.token
236
+ },
237
+ method: "GET"
238
+ }
239
+ winston.debug("DirAskGPTV2 check quote availability HttpRequest", HTTPREQUEST);
240
+
241
+ httpUtils.request(
242
+ HTTPREQUEST, async (err, resbody) => {
243
+ if (err) {
244
+ winston.error("DirAskGPTV2 Check quote availability err: ", err);
245
+ resolve(true)
246
+ } else {
247
+ if (resbody.isAvailable === true) {
248
+ resolve(true)
249
+ } else {
250
+ resolve(false)
251
+ }
252
+ }
253
+ }
254
+ )
255
+ })
256
+ }
257
+
258
+ async updateQuote(tokens_usage) {
259
+ return new Promise((resolve, reject) => {
260
+
261
+ const HTTPREQUEST = {
262
+ url: this.API_ENDPOINT + "/" + this.context.projectId + "/quotes/incr/tokens",
263
+ headers: {
264
+ 'Content-Type': 'application/json',
265
+ 'Authorization': 'JWT ' + this.context.token
266
+ },
267
+ json: tokens_usage,
268
+ method: "POST"
269
+ }
270
+ winston.debug("DirAskGPTV2 update quote HttpRequest ", HTTPREQUEST);
271
+
272
+ httpUtils.request(
273
+ HTTPREQUEST, async (err, resbody) => {
274
+ if (err) {
275
+ winston.error("DirAskGPTV2 Increment tokens quote err: ", err);
276
+ reject(false)
277
+ } else {
278
+ resolve(true);
279
+ }
280
+ }
281
+ )
282
+ })
283
+ }
284
+
285
+ async getNamespace(name, id) {
286
+ return new Promise((resolve) => {
287
+ const HTTPREQUEST = {
288
+ url: this.API_ENDPOINT + "/" + this.context.projectId + "/kb/namespace/all",
289
+ headers: {
290
+ 'Content-Type': 'application/json',
291
+ 'Authorization': 'JWT ' + this.context.token
292
+ },
293
+ method: "GET"
294
+ }
295
+ winston.debug("DirAskGPTV2 get all namespaces HttpRequest", HTTPREQUEST);
296
+ httpUtils.request(
297
+ HTTPREQUEST, async (err, namespaces) => {
298
+ if (err) {
299
+ winston.error("DirAskGPTV2 get all namespaces err: ", err);
300
+ resolve(null)
301
+ } else {
302
+ winston.debug("DirAskGPTV2 get all namespaces resbody: ", namespaces);
303
+ if (name) {
304
+ let namespace = namespaces.find(n => n.name === name);
305
+ resolve(namespace);
306
+ } else {
307
+ let namespace = namespaces.find(n => n.id === id);
308
+ resolve(namespace);
309
+ }
310
+
311
+ }
312
+ }
313
+ )
314
+ })
315
+ }
316
+
317
+ async setDefaultEngine() {
318
+ return new Promise((resolve) => {
319
+ let engine = {
320
+ name: "pinecone",
321
+ type: process.env.PINECONE_TYPE,
322
+ apikey: "",
323
+ vector_size: 1536,
324
+ index_name: process.env.PINECONE_INDEX
325
+ }
326
+ resolve(engine);
327
+ })
328
+ }
329
+
330
+ }
331
+
332
+ module.exports = { DirAddKbContent }