-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.js
1401 lines (1275 loc) · 56.2 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
/*
* Created with @iobroker/create-adapter v2.6.5
*/
const utils = require("@iobroker/adapter-core");
const axios = require("axios");
const fs = require("fs");
const mime = require("mime-types");
const AnthropicAiProvider = require("./lib/anthropic-ai-provider");
const OpenAiProvider = require("./lib/openai-ai-provider");
const PerplexityAiProvider = require("./lib/perplexity-ai-provider");
const OpenRouterAiProvider = require("./lib/openrouter-ai-provider");
const CustomAiProvider = require("./lib/custom-ai-provider");
class AiToolbox extends utils.Adapter {
/**
* @param [options] - The options object.
*/
constructor(options) {
super({
...options,
name: "ai-toolbox",
});
this.on("ready", this.onReady.bind(this));
this.on("stateChange", this.onStateChange.bind(this));
this.on("message", this.onMessage.bind(this));
this.on("unload", this.onUnload.bind(this));
this.timeouts = [];
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
if (this.config.bots.length == 0) {
this.log.warn("No tools set");
} else {
this.log.debug(`Found ${this.config.bots.length} tools`);
}
// Create Models and Tools objects
await this.setObjectAsync("Models", {
type: "device",
common: {
name: "AI Models",
},
native: {},
});
await this.setObjectAsync("Tools", {
type: "device",
common: {
name: "Created AI Tools",
},
native: {},
});
// Create objects for each model
const models = this.getAvailableModels();
for (let model of models) {
const modelName = model.value;
model = this.stringToAlphaNumeric(model.value);
this.log.debug(`Initializing objects for model: ${model}`);
await this.setObjectAsync(`Models.${model}`, {
type: "device",
common: {
name: model,
},
native: {},
});
await this.setObjectAsync(`Models.${model}.text_request`, {
type: "state",
common: {
name: "Request",
desc: "Start a direct request to the model with the entered text",
type: "string",
role: "text",
read: true,
write: true,
def: "",
},
native: {
model: modelName,
},
});
await this.setObjectNotExistsAsync(`Models.${model}.text_response`, {
type: "state",
common: {
name: "Response",
desc: "The response received from the model",
type: "string",
role: "text",
read: true,
write: false,
def: "",
},
native: {
model: modelName,
},
});
await this.setObjectAsync(`Models.${model}.statistics`, {
type: "device",
common: {
name: `Statistics for ${modelName}`,
},
native: {},
});
await this.setObjectAsync(`Models.${model}.response`, {
type: "device",
common: {
name: `Response data for ${modelName}`,
},
native: {},
});
await this.setObjectAsync(`Models.${model}.request`, {
type: "device",
common: {
name: `Request data for ${modelName}`,
},
native: {},
});
await this.setObjectNotExistsAsync(`Models.${model}.request.state`, {
type: "state",
common: {
name: "State for the running inference request",
type: "string",
role: "indicator",
read: true,
write: false,
def: "",
},
native: {},
});
await this.setObjectNotExistsAsync(`Models.${model}.request.body`, {
type: "state",
common: {
name: "Sent body for the running inference request",
type: "string",
role: "indicator",
read: true,
write: false,
def: "",
},
native: {},
});
await this.setObjectNotExistsAsync(`Models.${model}.response.raw`, {
type: "state",
common: {
name: "Raw response from model",
type: "string",
role: "indicator",
read: true,
write: false,
def: "",
},
native: {},
});
await this.setObjectNotExistsAsync(`Models.${model}.response.error`, {
type: "state",
common: {
name: "Error response from model",
type: "string",
role: "indicator",
read: true,
write: false,
def: "",
},
native: {},
});
await this.setObjectNotExistsAsync(`Models.${model}.statistics.tokens_input`, {
type: "state",
common: {
name: "Used input tokens for model",
type: "number",
role: "indicator",
read: true,
write: false,
def: 0,
},
native: {},
});
await this.setObjectNotExistsAsync(`Models.${model}.statistics.tokens_output`, {
type: "state",
common: {
name: "Used output tokens for model",
type: "number",
role: "indicator",
read: true,
write: false,
def: 0,
},
native: {},
});
await this.setObjectNotExistsAsync(`Models.${model}.statistics.requests_count`, {
type: "state",
common: {
name: "Count of requests for model",
type: "number",
role: "indicator",
read: true,
write: false,
def: 0,
},
native: {},
});
await this.setObjectNotExistsAsync(`Models.${model}.statistics.last_request`, {
type: "state",
common: {
name: "Last request for model",
type: "string",
role: "indicator",
read: true,
write: false,
def: "",
},
native: {},
});
}
// Create objects for each tool
for (const bot of this.config.bots) {
bot.bot_name = this.stringToAlphaNumeric(bot.bot_name);
this.log.debug(`Initializing objects for tool: ${bot.bot_name}`);
await this.setObjectAsync(`Tools.${bot.bot_name}`, {
type: "device",
common: {
name: bot.bot_name,
},
native: bot,
});
if (typeof bot.use_vision !== "undefined" && bot.use_vision) {
await this.setObjectAsync(`Tools.${bot.bot_name}.image_url`, {
type: "state",
common: {
name: "Image URL",
desc: "URL of an image to send with the next text request",
type: "string",
role: "text",
read: true,
write: true,
def: "",
},
native: {},
});
}
await this.setObjectAsync(`Tools.${bot.bot_name}.text_request`, {
type: "state",
common: {
name: "Request",
desc: "Start a request to the tool with the entered text",
type: "string",
role: "text",
read: true,
write: true,
def: "",
},
native: bot,
});
await this.setObjectNotExistsAsync(`Tools.${bot.bot_name}.text_response`, {
type: "state",
common: {
name: "Response",
desc: "The response received from the tool",
type: "string",
role: "text",
read: true,
write: false,
def: "",
},
native: bot,
});
await this.setObjectAsync(`Tools.${bot.bot_name}.statistics`, {
type: "device",
common: {
name: `Statistics for ${bot.bot_name}`,
},
native: {},
});
await this.setObjectAsync(`Tools.${bot.bot_name}.response`, {
type: "device",
common: {
name: `Response data for ${bot.bot_name}`,
},
native: {},
});
await this.setObjectAsync(`Tools.${bot.bot_name}.request`, {
type: "device",
common: {
name: `Request data for ${bot.bot_name}`,
},
native: {},
});
await this.setObjectNotExistsAsync(`Tools.${bot.bot_name}.statistics.messages`, {
type: "state",
common: {
name: "Message history",
desc: `Previous messages for tool ${bot.bot_name}`,
type: "string",
role: "text",
read: true,
write: false,
def: '{"messages": []}',
},
native: {},
});
await this.setObjectAsync(`Tools.${bot.bot_name}.statistics.clear_messages`, {
type: "state",
common: {
name: "Clear previous message history",
type: "boolean",
role: "button",
read: true,
write: true,
def: true,
},
native: bot,
});
await this.setObjectNotExistsAsync(`Tools.${bot.bot_name}.request.state`, {
type: "state",
common: {
name: "State for the running inference request",
type: "string",
role: "indicator",
read: true,
write: false,
def: "",
},
native: {},
});
await this.setObjectNotExistsAsync(`Tools.${bot.bot_name}.request.body`, {
type: "state",
common: {
name: "Sent body for the running inference request",
type: "string",
role: "indicator",
read: true,
write: false,
def: "",
},
native: {},
});
await this.setObjectNotExistsAsync(`Tools.${bot.bot_name}.response.raw`, {
type: "state",
common: {
name: "Raw response from tool",
type: "string",
role: "indicator",
read: true,
write: false,
def: "",
},
native: {},
});
await this.setObjectNotExistsAsync(`Tools.${bot.bot_name}.response.error`, {
type: "state",
common: {
name: "Error response from tool",
type: "string",
role: "indicator",
read: true,
write: false,
def: "",
},
native: {},
});
await this.setObjectNotExistsAsync(`Tools.${bot.bot_name}.statistics.tokens_input`, {
type: "state",
common: {
name: "Used input tokens for tool",
type: "number",
role: "indicator",
read: true,
write: false,
def: 0,
},
native: {},
});
await this.setObjectNotExistsAsync(`Tools.${bot.bot_name}.statistics.tokens_output`, {
type: "state",
common: {
name: "Used output tokens for tool",
type: "number",
role: "indicator",
read: true,
write: false,
def: 0,
},
native: {},
});
await this.setObjectNotExistsAsync(`Tools.${bot.bot_name}.statistics.requests_count`, {
type: "state",
common: {
name: "Count of requests for tool",
type: "number",
role: "indicator",
read: true,
write: false,
def: 0,
},
native: {},
});
await this.setObjectNotExistsAsync(`Tools.${bot.bot_name}.statistics.last_request`, {
type: "state",
common: {
name: "Last request for tool",
type: "string",
role: "indicator",
read: true,
write: false,
def: "",
},
native: {},
});
}
this.log.debug(`Available models: ${JSON.stringify(this.getAvailableModels())}`);
this.subscribeStates("*");
this.log.info("Adapter ready");
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
*
* @param callback - The callback function.
*/
onUnload(callback) {
try {
for (const timeout of this.timeouts) {
clearTimeout(timeout);
}
callback();
} catch (e) {
this.log.error(`Error on unload: ${e}`);
callback();
}
}
/**
* Is called if a subscribed state changes
*
* @param id - The state ID that changed.
* @param state - The state object.
*/
async onStateChange(id, state) {
if (state) {
// The state was changed
this.log.debug(`state ${id} changed: ${state.val} (ack = ${state.ack})`);
if (id.includes(".clear_messages") && state.val) {
const bot = await this.getObjectAsync(id);
if (bot) {
bot.native.bot_name = this.stringToAlphaNumeric(bot.native.bot_name);
this.log.debug(`Clearing message history for tool ${bot.native.bot_name}`);
await this.setStateAsync(`Tools.${bot.native.bot_name}.statistics.messages`, {
val: '{"messages": []}',
ack: true,
});
await this.setStateAsync(`Tools.${bot.native.bot_name}.response.raw`, {
val: null,
ack: true,
});
await this.setStateAsync(`Tools.${bot.native.bot_name}.text_response`, {
val: null,
ack: true,
});
await this.setStateAsync(`Tools.${bot.native.bot_name}.response.error`, {
val: null,
ack: true,
});
await this.setStateAsync(`Tools.${bot.native.bot_name}.request.body`, {
val: null,
ack: true,
});
await this.setStateAsync(`Tools.${bot.native.bot_name}.request.state`, {
val: null,
ack: true,
});
}
}
if (id.includes("Tools.") && id.includes(".text_request") && state.val) {
const bot = await this.getObjectAsync(id);
if (bot) {
if (bot.native.use_vision) {
const imageUrl = await this.getStateAsync(`Tools.${bot.native.bot_name}.image_url`);
if (imageUrl && imageUrl.val && imageUrl.val != "") {
const imageData = await this.fetchImageAsBase64(imageUrl.val);
if (imageData.success) {
await this.setStateAsync(`Tools.${bot.native.bot_name}.image_url`, {
val: "",
ack: true,
});
this.startBotRequest(bot.native, state.val, imageData);
} else {
this.log.warn(
`Request stopped, image fetch failed for tool ${bot.native.bot_name} URL: ${
imageUrl.val
}`,
);
await this.setStateAsync(`Tools.${bot.native.bot_name}.request.state`, {
val: "error",
ack: true,
});
await this.setStateAsync(`Tools.${bot.native.bot_name}.response.error`, {
val: "fetching image for request failed",
ack: true,
});
await this.setStateAsync(`Tools.${bot.native.bot_name}.image_url`, {
val: "",
ack: true,
});
}
} else {
this.startBotRequest(bot.native, state.val, null);
}
} else {
this.startBotRequest(bot.native, state.val, null);
}
}
}
if (id.includes("Models.") && id.includes(".text_request") && state.val) {
const obj = await this.getObjectAsync(id);
if (obj) {
this.startModelRequest(obj.native.model, [{ role: "user", content: state.val }]);
}
}
}
}
/**
* Starts a request for the selected tool with the specified text.
* Validates the message history and adds the message pair to the history.
* Updates the statistics for the tool with the response data.
* Starts a new request if the previous request failed.
* Logs the request and response data.
* Returns the response data if the request was successful, otherwise false.
*
* @param bot - The bot configuration object.
* @param text - The text to send to the bot.
* @param image - The image to send to the bot.
* @param tries - The number of tries for the request.
* @param try_only_once - If true, the request will only be tried once.
*/
async startBotRequest(bot, text, image = null, tries = 0, try_only_once = false) {
bot.bot_name = this.stringToAlphaNumeric(bot.bot_name);
this.log.info(`Starting request for tool: ${bot.bot_name} Text: ${text}`);
if (tries == 0) {
await this.setStateAsync(`Tools.${bot.bot_name}.request.state`, { val: "start", ack: true });
}
await this.setStateAsync(`Tools.${bot.bot_name}.response.error`, { val: "", ack: true });
const provider = this.getModelProvider(bot.bot_model);
if (provider) {
if (!provider.apiTokenCheck()) {
this.log.warn(`No API token set for provider ${typeof provider}, cant start request!`);
return false;
}
const messages = [];
let messagePairs = { messages: [] };
if (bot.chat_history > 0) {
this.log.debug(`Chat history is enabled for tool ${bot.bot_name}`);
messagePairs = await this.getValidatedMessageHistory(bot);
this.log.debug(`Adding previous message pairs for request: ${JSON.stringify(messagePairs)}`);
}
if (
bot.bot_example_request &&
bot.bot_example_request != "" &&
bot.bot_example_response &&
bot.bot_example_response != ""
) {
messagePairs.messages.unshift({ user: bot.bot_example_request, assistant: bot.bot_example_response });
this.log.debug(`Adding tool example message pair for request: ${JSON.stringify(messagePairs)}`);
}
this.log.debug("Converting message pairs to chat format for request to model");
for (const message of messagePairs.messages) {
if (typeof message.image !== "undefined" && message.image != null) {
this.log.debug(
`Tool ${bot.bot_name} image message detected in chat history message, adding image data`,
);
messages.push({ role: "user", content: message.user, image: message.image });
} else {
messages.push({ role: "user", content: message.user });
}
messages.push({ role: "assistant", content: message.assistant });
}
this.log.debug(`Adding user message to request array: ${text}`);
if (image) {
this.log.debug(`Tool ${bot.bot_name} image request detected, adding image data`);
messages.push({ role: "user", content: text, image: image });
} else {
messages.push({ role: "user", content: text });
}
let modelResponse = {};
modelResponse = await this.startModelRequest(
bot.bot_model,
messages,
bot.bot_system_prompt,
bot.max_tokens,
bot.temperature,
);
let requestCompleted = true;
if (modelResponse.error) {
await this.setStateAsync(`Tools.${bot.bot_name}.request.state`, { val: "error", ack: true });
await this.setStateAsync(`Tools.${bot.bot_name}.request.body`, {
val: JSON.stringify(modelResponse.requestData),
ack: true,
});
await this.setStateAsync(`Tools.${bot.bot_name}.response.error`, {
val: modelResponse.error,
ack: true,
});
await this.setStateAsync(`Tools.${bot.bot_name}.response.raw`, {
val: JSON.stringify(modelResponse.responseData),
ack: true,
});
requestCompleted = false;
} else {
await this.setStateAsync(`Tools.${bot.bot_name}.request.state`, { val: "success", ack: true });
await this.setStateAsync(`Tools.${bot.bot_name}.request.body`, {
val: JSON.stringify(modelResponse.requestData),
ack: true,
});
await this.setStateAsync(`Tools.${bot.bot_name}.response.error`, { val: "", ack: true });
await this.setStateAsync(`Tools.${bot.bot_name}.response.raw`, {
val: JSON.stringify(modelResponse.responseData),
ack: true,
});
await this.setStateAsync(`Tools.${bot.bot_name}.text_response`, {
val: modelResponse.text,
ack: true,
});
this.updateBotStatistics(bot, modelResponse);
}
if (!requestCompleted) {
if (typeof bot.retry_delay == "undefined") {
bot.retry_delay = 15;
}
if (typeof bot.max_retries == "undefined") {
bot.max_retries = 3;
}
await this.setStateAsync(`Tools.${bot.bot_name}.request.state`, { val: "retry", ack: true });
if (tries < bot.max_retries && !try_only_once) {
let retry_delay = bot.retry_delay * 1000;
if (tries == bot.max_retries) {
retry_delay = 0;
}
this.log.debug(
`Try ${tries}${1}/${bot.max_retries} of request for tool ${bot.bot_name} failed Text: ${text}`,
);
tries = tries + 1;
this.log.debug(
`Retry request for tool ${bot.bot_name} in ${bot.retry_delay} seconds Text: ${text}`,
);
this.timeouts.push(
setTimeout(
(bot, tries) => {
this.startBotRequest(bot, text, image, tries);
},
retry_delay,
bot,
tries,
),
);
} else {
this.log.error(
`Request for tool ${bot.bot_name} failed after ${bot.max_retries} tries Text: ${text}`,
);
await this.setStateAsync(`Tools.${bot.bot_name}.request.state`, { val: "failed", ack: true });
return false;
}
} else {
this.log.info(
`Request for tool ${bot.bot_name} successful Text: ${text} Response: ${modelResponse.text}`,
);
await this.addMessagePairToHistory(
bot,
text,
image,
modelResponse.text,
modelResponse.tokens_input,
modelResponse.tokens_output,
modelResponse.model,
);
return modelResponse;
}
}
}
/**
* Starts a request for the specified model with the specified messages.
* Validates the request and returns the response data if the request was successful.
* Updates the statistics for the model with the response data.
* Logs the request and response data.
*
* @param model - The model name.
* @param messages - The messages to send to the model.
* @param system_prompt - The system prompt for the model.
* @param max_tokens - The maximum number of tokens to generate.
* @param temperature - The temperature for the model.
* @returns - Returns the response data if the request was successful, otherwise false.
*/
async startModelRequest(model, messages, system_prompt = null, max_tokens = 2000, temperature = 0.6) {
const modelDatapointName = this.stringToAlphaNumeric(model);
this.log.info(`Starting request for model: ${model} Messages: ${JSON.stringify(messages)}`);
const provider = this.getModelProvider(model);
if (provider) {
if (!provider.apiTokenCheck()) {
this.log.warn(`No API token set for provider ${typeof provider}, cant start request!`);
return false;
}
await this.setStateAsync(`Models.${modelDatapointName}.request.state`, { val: "start", ack: true });
await this.setStateAsync(`Models.${modelDatapointName}.response.error`, { val: "", ack: true });
const request = {
model: model,
messages: messages,
max_tokens: max_tokens,
temperature: temperature,
system_prompt: system_prompt,
feedback_device: `Model.${modelDatapointName}`,
};
if (!this.validateRequest(request)) {
await this.setStateAsync(`Models.${modelDatapointName}.request.state`, {
val: "error",
ack: true,
});
await this.setStateAsync(`Models.${modelDatapointName}.response.error`, {
val: "Request Validation failed",
ack: true,
});
this.log.warn(`Request for Model ${model} failed validation, stopping request`);
return;
}
const modelResponse = await provider.request(request);
modelResponse.requestData = provider.requestData;
modelResponse.responseData = provider.responseData;
if (modelResponse.error) {
await this.setStateAsync(`Models.${modelDatapointName}.request.state`, {
val: "error",
ack: true,
});
await this.setStateAsync(`Models.${modelDatapointName}.response.error`, {
val: modelResponse.error,
ack: true,
});
await this.setStateAsync(`Models.${modelDatapointName}.request.body`, {
val: JSON.stringify(modelResponse.requestData),
ack: true,
});
await this.setStateAsync(`Models.${modelDatapointName}.response.raw`, {
val: JSON.stringify(modelResponse.responseData),
ack: true,
});
} else {
await this.setStateAsync(`Models.${modelDatapointName}.request.state`, {
val: "success",
ack: true,
});
await this.setStateAsync(`Models.${modelDatapointName}.response.error`, { val: "", ack: true });
await this.setStateAsync(`Models.${modelDatapointName}.request.body`, {
val: JSON.stringify(modelResponse.requestData),
ack: true,
});
await this.setStateAsync(`Models.${modelDatapointName}.response.raw`, {
val: JSON.stringify(modelResponse.responseData),
ack: true,
});
await this.setStateAsync(`Models.${modelDatapointName}.text_response`, {
val: modelResponse.text,
ack: true,
});
this.updateModelStatistics(model, modelResponse);
}
return modelResponse;
}
}
/**
* Validates the request object and sets default values if necessary.
* Logs a warning if the request is invalid.
* Returns the validated request object or false if the request is invalid.
*
* @param {object} requestObj - The request object.
* @param requestObj.model - The model name.
* @param requestObj.messages - The messages to send to the model.
* @param requestObj.feedback_device - The feedback device for the model.
* @param requestObj.max_tokens - The maximum number of tokens to generate.
* @param requestObj.temperature - The temperature for the model.
* @param requestObj.system_prompt - The system prompt for the model.
* @returns - The validated request object or false if the request is invalid.
*/
validateRequest(requestObj) {
if (!requestObj.model || requestObj.model == "") {
this.log.warn(`No model provided in request, validation failed`);
return false;
}
if (!requestObj.messages || requestObj.messages.length == 0) {
this.log.warn(`No messages provided in request, validation failed`);
return false;
}
if (!requestObj.feedback_device || requestObj.feedback_device == "") {
this.log.debug(`No path for feedback objects provided in request, using Model default`);
requestObj.feedback_device = `Models.${this.stringToAlphaNumeric(requestObj.model)}`;
}
if (!requestObj.max_tokens || requestObj.max_tokens == "") {
this.log.debug(`No max_tokens provided in request, using default value: 2000`);
requestObj.max_tokens = 2000;
}
if (!requestObj.temperature || requestObj.temperature == "") {
this.log.debug(`No temperature provided in request, using default value: 0.6`);
requestObj.temperature = 0.6;
}
if (!requestObj.system_prompt || requestObj.system_prompt.trim() == "") {
this.log.debug(`No system prompt provided in request`);
requestObj.system_prompt = null;
}
return requestObj;
}
/**
* Retrieves the message history for the specified bot.
* Validates the message history and returns an array of messages.
*
* @param bot - The bot configuration object.
* @returns Object - The validated message history object.
*/
async getValidatedMessageHistory(bot) {
bot.bot_name = this.stringToAlphaNumeric(bot.bot_name);
this.log.debug("Getting previous message pairs for request");
const validatedObject = { messages: [] };
const messageObject = await this.getStateAsync(`Tools.${bot.bot_name}.statistics.messages`);
if (messageObject && messageObject.val != null && messageObject.val != "") {
this.log.debug(`Message history object for ${bot.bot_name} found data: ${messageObject.val}`);
this.log.debug(`Trying to decode history json data: ${messageObject.val}`);
const messagesData = JSON.parse(messageObject.val);
if (messagesData && messagesData.messages && messagesData.messages.length > 0) {
for (const message of messagesData.messages) {
if (typeof bot.include_vision_in_history !== "undefined" && bot.include_vision_in_history) {
validatedObject.messages.push(message);
} else {
if (message.image) {
delete message.image;
}
validatedObject.messages.push(message);
}
}
}
this.log.debug(`Validated object: ${JSON.stringify(validatedObject)}`);
return validatedObject;
}
this.log.warn(`Message history object for ${bot.bot_name} not found`);
return validatedObject;
}
/**
* Adds a message pair to the message history for the specified bot.
*
* @param bot - The bot configuration object.
* @param user - The user message.
* @param image - The image data.
* @param assistant - The assistant response.
* @param tokens_input - The number of input tokens used in the request.
* @param tokens_output - The number of output tokens used in the response.
* @param model - The model name.
* @returns - Returns true if the message pair was added successfully, otherwise false.
*/
async addMessagePairToHistory(bot, user, image, assistant, tokens_input, tokens_output, model) {
if (bot.chat_history > 0) {
bot.bot_name = this.stringToAlphaNumeric(bot.bot_name);
const messagesData = await this.getValidatedMessageHistory(bot);
this.log.debug(`Adding to message object with data: ${JSON.stringify(messagesData)}`);
messagesData.messages.push({
user: user,
assistant: assistant,
image: image,
timestamp: Date.now(),
model: model,
tokens_input: tokens_input,
tokens_output: tokens_output,
});
this.log.debug(`New message object: ${JSON.stringify(messagesData)}`);
while (messagesData.messages.length > bot.chat_history) {
this.log.debug("Removing message entry because chat history too big");
messagesData.messages.shift();
}
this.log.debug(`Final message object: ${JSON.stringify(messagesData)}`);
await this.setStateAsync(`Tools.${bot.bot_name}.statistics.messages`, {
val: JSON.stringify(messagesData),
ack: true,
});
return true;
}
this.log.debug(`Chat history disabled for tool ${bot.bot_name}`);
return false;
}
/**
* Updates the statistics for the specified bot with the response data.
*
* @param bot - The bot configuration object.
* @param {object} response - The response from the assistant.
* @param response.tokens_input - The number of input tokens used in the request.
* @param response.tokens_output - The number of output tokens used in the response.
*/
async updateBotStatistics(bot, response) {
bot.bot_name = this.stringToAlphaNumeric(bot.bot_name);
this.log.debug(`Updating statistics for tool ${bot.bot_name} with response: ${JSON.stringify(response)}`);
let input_tokens = await this.getStateAsync(`Tools.${bot.bot_name}.statistics.tokens_input`);
let output_tokens = await this.getStateAsync(`Tools.${bot.bot_name}.statistics.tokens_output`);
let requests_count = await this.getStateAsync(`Tools.${bot.bot_name}.statistics.requests_count`);
if (!input_tokens || input_tokens.val == null || input_tokens.val == "") {
input_tokens = 0 + response.tokens_input;
} else {
input_tokens = input_tokens.val + response.tokens_input;
}
if (!output_tokens || output_tokens.val == null || output_tokens.val == "") {
output_tokens = 0 + response.tokens_output;
} else {
output_tokens = output_tokens.val + response.tokens_output;
}
if (!requests_count || requests_count.val == null || requests_count.val == "") {
requests_count = 0 + 1;
} else {
requests_count = parseInt(requests_count.val) + 1;
}
this.setStateAsync(`Tools.${bot.bot_name}.statistics.tokens_input`, { val: input_tokens, ack: true });
this.setStateAsync(`Tools.${bot.bot_name}.statistics.tokens_output`, { val: output_tokens, ack: true });
this.setStateAsync(`Tools.${bot.bot_name}.statistics.requests_count`, { val: requests_count, ack: true });
this.setStateAsync(`Tools.${bot.bot_name}.statistics.last_request`, {
val: new Date().toISOString(),
ack: true,
});
}