-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
2790 lines (2455 loc) · 108 KB
/
index.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
// index.js - Command-line chat interface to ollama, Groq, OpenAI, and Anthropic models with audio and function calling tools (games, data management, code runner, etc.)
// See: https://ollama.com, https://ollama.com/library, and
// https://github.com/ollama/ollama?tab=readme-ov-file#quickstart
// https://www.npmjs.com/package/groq-sdk
// https://www.npmjs.com/package/openai
// https://www.npmjs.com/package/@anthropic-ai/sdk
// https://www.npmjs.com/package/axios
// https://www.npmjs.com/package/yargs
// For text to speech audio:
// https://www.npmjs.com/package/elevenlabs
// https://www.npmjs.com/package/@deepgram/sdk
const fs = require('fs');
const path = require('path');
const util = require('util');
const readline = require('readline');
const axios = require('axios');
const Groq = require('groq-sdk');
const { performance, PerformanceObserver } = require('perf_hooks');
const { ElevenLabsClient, play, stream: playStream } = require("elevenlabs");
const { createClient: createDeepgramClient } = require("@deepgram/sdk");
const Anthropic = require("@anthropic-ai/sdk");
const OpenAI = require('openai');
require('dotenv').config();
const applicationName = "llm-experiments";
// Set the path for the log file
const errorFilePath = path.join(__dirname, 'logs', `${applicationName}.errors.log`);
const infoFilePath = path.join(__dirname, 'logs', `${applicationName}.info.log`);
const debugFilePath = path.join(__dirname, 'logs', `${applicationName}.debug.log`);
const traceFilePath = path.join(__dirname, 'logs', `${applicationName}.trace.log`);
// Create a writable stream to the log files
const errorLogStream = fs.createWriteStream(errorFilePath, { flags: 'a' });
const infoLogStream = fs.createWriteStream(infoFilePath, { flags: 'a' });
const debugLogStream = fs.createWriteStream(debugFilePath, { flags: 'a' });
const traceLogStream = fs.createWriteStream(traceFilePath, { flags: 'a' });
console.error = function (message, ...optionalParams) {
errorLogStream.write(`${new Date().toISOString()} - ${util.format(message, ...optionalParams)}\n`);
};
console.info = function (message, ...optionalParams) {
infoLogStream.write(`${new Date().toISOString()} - ${util.format(message, ...optionalParams)}\n`);
};
console.debug = function (message, ...optionalParams) {
debugLogStream.write(`${new Date().toISOString()} - ${util.format(message, ...optionalParams)}\n`);
};
console.trace = function (message, ...optionalParams) {
traceLogStream.write(`${new Date().toISOString()} - ${util.format(message, ...optionalParams)}\n`);
};
const {
prompts,
getPrompt,
system_message_metadata_tools_epilogue,
system_message_metadata_schema_tools_part,
system_message_metadata_schema_arguments,
system_message_metadata_schema_with_tools,
system_message_metadata_schema_without_tools,
system_message_metadata_schema_tool_only,
} = require('./lib/prompts');
let {
system_message_metadata,
system_message_metadata2,
system_message_metadata_schema
} = require('./lib/prompts');
const {
randomPersona,
assistantPersonas
} = require('./lib/persona');
const {
JsonStorage,
RuntimeMemoryStorage,
nodeCodeRunner,
extractAndParseJsonBlock
} = require('./lib/utils');
const {
indexSourcesRAG,
findSourcesRAG
} = require('./lib/rag');
const jsonStorageFile = path.join(__dirname, 'data', 'persistent.json');
const jsonStorage = new JsonStorage(jsonStorageFile);
const runtimeMemoryStorage = new RuntimeMemoryStorage();
const {
createHangmanGame,
createFireWaterGrassGame,
createRockPaperScissorsGame,
createNumberGuessingGame,
createHeadsOrTailsGame
} = require('./lib/games');
const hangmanGame = createHangmanGame();
const headsOrTailsGame = createHeadsOrTailsGame();
const fireWaterGrassGame = createFireWaterGrassGame();
const rockPaperScissorsGame = createRockPaperScissorsGame();
// createNumberGuessingGame() will be constructed for each game
let numberGuessingGame = null;
const { argv } = require('./lib/args');
const { renderSelectedSchemas } = require('./lib/tools');
// Initialize the GROQ SDK with the API key
const groq = new Groq({
apiKey: process.env.GROQ_API_KEY
});
// Global constants
const groqModelNames = [
"llama3-70b-8192",
"llama3-8b-8192",
"llama2-70b-4096",
"gemma-7b-it",
"mixtral-8x7b-32768"
];
const anthropicModelNames = [
"claude-3-haiku-20240307",
"claude-3-sonnet-20240229",
"claude-3-opus-20240229"
]
const openAIModelNames = [
"gpt-4-turbo-2024-04-09",
"gpt-4-turbo",
"gpt-3.5-turbo-0125",
"gpt-3.5-turbo"
]
const ttsServices = ["elevenlabs", "deepgram"];
const sttServices = ["google", "deepgram"];
// Eleven Labs voice ID: '29vD33N1CtxCmqQRPOHJ' -> Male voice (Drew)
// Deepgram voice ID: 'aura-asteria-en' -> Aura Asteria English
const defaultVoices = {
"elevenlabs": "29vD33N1CtxCmqQRPOHJ",
"deepgram": "aura-asteria-en"
};
const promptIcon = "➤ ";
// Console input/output handler
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: promptIcon
});
// Ollama server base URL
const baseUrl = 'http://localhost:11434';
// Async request performance log file
const performanceLogFilepath = path.join(__dirname, 'data', 'performance_logs.csv');
// Default temperature for LLM generated text
const temperature = 0.0;
// Activity indicator with spinner on command line interface
const stopSpinner = { isStopped: true };
// Create a session directory
const sessionStart = getCurrentTimestamp();
const sessionDir = path.join(__dirname, 'chats', sessionStart);
const sessionFile = path.join(sessionDir, 'session.jsonl');
const agentsResponsesDir = path.join(sessionDir, 'agents');
const agentsResponsesFile = path.join(agentsResponsesDir, 'responses.jsonl');
const elevenlabs = new ElevenLabsClient({
apiKey: process.env.ELEVENLABS_API_KEY
})
const deepgram = createDeepgramClient(
process.env.DEEPGRAM_API_KEY
);
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY
});
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
const audioRecorders = {
"google": require('./lib/recorders/GoogleVoiceRecognition'),
"deepgram": require('./lib/recorders/DeepgramVoiceRecognition')
};
let voiceRecognition;
let audioRecorder;
let voiceRecognitionStopWord;
/****************************************************
** Global variables
****************************************************/
// LLM client: ollama or groq
// TODO: openai, anthropic, huggingface, etc.
let llmClient = "ollama";
// How many messages should fit on history. odd number it must be!
let messageLimit = 11;
// After which amount of new messages should the summary be generated
let summarizeInterval = 10;
let variables = {};
let model = "";
// Note: stream mode does not suite with well with non-tool games, because the logic
// is based on the response text, which should be all available before
// doing conjectures from the input.
let stream = null;
// Applicable with ollama client only. Other clients are always in chat mode
let chat = true;
let summary = "";
let messages = [];
let contextIds = [];
let modelNames = [];
let tools = "";
let assistantPersona = "Snarky Assistant";
// Eleven Labs voice ID: '29vD33N1CtxCmqQRPOHJ' -> Male voice (Drew)
// Deepgram voice ID: 'aura-asteria-en' -> Aura Asteria English
let voiceId = "aura-asteria-en"
// Text to speech service: elevenlabs, deepgram
let textToSpeechService = '';
//let speechToTextService = 'deepgram';
let hideToolJSONOutput;
/****************************************************
** Generators
****************************************************/
// Generate a summary of the user's message
const summaryGenerators = {
"groq": (userMessage, model = "llama3-70b-8192") => {
return generateSummary(userMessage, model, groqPromptRequest);
},
"ollama": (userMessage, model = "llama3") => {
return generateSummary(userMessage, model, ollamaPromptRequest);
},
"anthropic": (userMessage, model = "claude-3-haiku-20240307") => {
return generateSummary(userMessage, model, claudePromptRequest);
},
"openai": (userMessage, model = "gpt-3.5-turbo-0125") => {
return generateSummary(userMessage, model, gPTPromptRequest);
}
}
// Generate a response to the user's prompt
const responseGenerators = {
"groq": sendRequestAndRetrieveResponseGroq,
"ollama": sendRequestAndRetrieveResponse,
"anthropic": sendRequestAndRetrieveResponseClaude,
"openai": sendRequestAndRetrieveResponseGPT
}
// Generate a tool metadata for the prompt
const toolGenerators = {
"groq": sendRequestAndRetrieveResponseGroq,
"ollama": sendRequestAndRetrieveResponse,
"anthropic": sendRequestAndRetrieveResponseClaude,
"openai": sendRequestAndRetrieveResponseGPT
}
// Generate a suggestion for the user's prompt
const suggestionGenerators = {
"groq": sendRequestAndRetrieveResponseGroq,
"ollama": sendRequestAndRetrieveResponse,
"anthropic": sendRequestAndRetrieveResponseClaude,
"openai": sendRequestAndRetrieveResponseGPT
};
// Generate a response to the user's prompt
const agentGenerators = {
"groq": sendRequestAndRetrieveResponseGroq,
"ollama": sendRequestAndRetrieveResponse,
"anthropic": sendRequestAndRetrieveResponseClaude,
"openai": sendRequestAndRetrieveResponseGPT
}
/****************************************************
** Functions
****************************************************/
// Text to speech related
async function tts(text) {
// tts service not set.
if (textToSpeechService == '') {
return;
}
// Check if text to speech service exists
if (!textToSpeechInterfaces[textToSpeechService]) {
console.warn(`Text to speech service '${textToSpeechService}' is not supported.`);
return;
}
// Check if voice exists
if (!textToSpeechVoices[textToSpeechService][voiceId]) {
console.warn(`Voice ID '${voiceId}' is not available for the service '${textToSpeechService}'.`);
return;
}
// Play the text as speech
try {
await textToSpeechInterfaces[textToSpeechService](text).catch(error => {
console.warn(`Error calling ${textToSpeechService}:`, error);
});
// Wait for 500ms after the speech function call
//await new Promise(resolve => setTimeout(resolve, 1000));
} catch (error) {
console.warn(`Text to speech failed: ${error.message}`);
}
}
const textToSpeechInterfaces = {
"elevenlabs": textToSpeechElevenLabs,
"deepgram": textToSpeechDeepGram
}
const speechToTextInterfaces = {
"deepgram": speechToTextDeepgram
}
const textToSpeechVoices = {
"elevenlabs": {
"29vD33N1CtxCmqQRPOHJ": {
"name": "Drew",
"settings": {
stability: 0.95,
similarity_boost: 0.75,
style: 0.06,
use_speaker_boost: true
}
},
},
"deepgram": {
"aura-asteria-en": {
"name": "Aura Asteria English",
"settings": {}
},
}
}
function speechToTextDeepgram() {
console.log("Speech to text with Deepgram is not implemented yet.");
}
async function textToSpeechDeepGram(text) {
try {
const response = await deepgram.speak.request({ text: text }, { model: voiceId });
const streamAudio = await response.getStream();
if (streamAudio) {
// Using elevenlabs stream player!
await playStream(streamAudio);
} else {
throw new Error("Failed to obtain audio stream.");
}
} catch (error) {
console.warn("An error occurred in textToSpeechDeepGram:", error);
}
}
/*
async function textToSpeechElevenLabs_(text) {
elevenLabs.textToSpeech(voiceId, text, "elevenlabs_multilingual_v2",
textToSpeechVoices[textToSpeechService][voiceId]["settings"]).then(async (res) => {
const pipe = await res.pipe;
pipe(fs.createWriteStream("test-with-pipe.mp3"));
}
);
}
*/
async function textToSpeechElevenLabs(text) {
try {
const data = {
text: text,
model_id: "eleven_multilingual_v2"
};
// Ensure voiceId is defined before this call, or pass it as a parameter
const streamAudio = await elevenlabs.textToSpeech.convertAsStream(voiceId, data);
await playStream(streamAudio);
// await play(audio); // Uncomment if this is needed and correct
} catch (error) {
console.warn("An error occurred in textToSpeechElevenLabs:", error);
// Handle or log the error appropriately here
}
}
/****************************************************
** Tools
****************************************************/
const numberGuessing = (kwargs) => {
try {
if (kwargs.init_game) {
// Initialize a new game and sanitize the arguments
const min = parseInt(kwargs.init_game.min);
const max = parseInt(kwargs.init_game.max);
const guesses = parseInt(kwargs.init_game.guesses);
// Validate the input
if (min >= max) {
return { success: false, message: "Invalid range. The minimum value must be less than the maximum value." };
}
if (guesses <= 1) {
return { success: false, message: "Invalid number of guesses. The number of guesses must be greater than one." };
}
numberGuessingGame = createNumberGuessingGame(min, max, guesses);
return { success: true, message: `New number guessing game initialized with range ${min}-${max} and ${guesses} guesses allowed. Guesses before or at the initialization are not accounted.` };
} else if (kwargs.guess_number) {
// Make a guess
const number = parseInt(kwargs.guess_number);
return numberGuessingGame(number);
} else {
return { success: false, message: "No valid arguments provided for the game." };
}
} catch (error) {
console.error("Error in number guessing game:", error);
return { success: false, message: "An error occurred while executing the number guessing game." };
}
};
const headsOrTails = (kwargs) => {
try {
if (kwargs.user_input) {
return headsOrTailsGame(kwargs.user_input.trim());
} else {
return { success: false, message: "No valid arguments provided for the game." };
}
} catch (error) {
console.error("Error in heads-or-tails game:", error);
return { success: false, message: "An error occurred while executing the heads-or-tails game." };
}
};
const hangman = (kwargs) => {
try {
if (kwargs.init_word) {
// Initialize the game
const word = kwargs.init_word.trim().toLowerCase();
// If word has any special characters, return error
if (word.match(/[^a-z]/)) {
return { success: false, message: "Invalid word. Please provide a word with only letters." };
}
return hangmanGame.init(word);
}
else if (kwargs.guess_letter) {
// Play the game, guess a letter
const letter = kwargs.guess_letter.trim().toLowerCase();
return hangmanGame.play(letter);
} else if (kwargs.guess_word) {
// Guess the word, makes sense to guess the word before all letters are guessed
const word = kwargs.guess_word.trim().toLowerCase();
return hangmanGame.guess(word);
} else {
return { success: false, message: `No valid arguments ${JSON.stringify(kwargs)} provided for the game.` };
}
} catch (error) {
console.error("Error in hangman game:", error);
console.log(JSON.stringify({ success: false, message: "An error occurred while executing the hangman game." }));
}
};
const gameDispatcher = (game, kwargs) => {
try {
if (kwargs.init_game) {
// Initializes a new game
return game.init();
} else if (kwargs.player_move) {
// Player makes a move
const move = kwargs.player_move.trim().toLowerCase();
if (!game.elements.includes(move)) {
return { success: false, message: `Invalid move. Please choose one of ${game.elements.join(', ')}.` };
}
return game.playRound(move);
} else if (kwargs.get_score) {
// Retrieves the current score
return game.getScore();
} else {
return { success: false, message: `No valid arguments ${JSON.stringify(kwargs)} provided for the game.` };
}
} catch (error) {
console.error(`Error in ${game.name}Game:`, error);
return { success: false, message: `An error occurred while executing the ${game.name} game.` };
}
};
function upsertDataEntry({ key, value, key_group = "default" }) {
if (!key || !value || !key_group) {
return { success: false, message: "Missing required arguments. Please provide key, value, and key_group." };
}
try {
jsonStorage.upsert(key, value, key_group);
return { success: true, message: `Data entry with key '${key}' and value '${value}' stored in group '${key_group}'.` };
} catch (error) {
return { success: false, message: `Error storing data: ${error.message}` };
}
}
function retrieveDataEntry({ field, value }) {
if (!field || !value) {
return { success: false, message: "Missing required arguments. Please provide field and value." };
}
try {
const result = jsonStorage.retrieve(field, value);
if (result) {
return { success: true, message: `Data entry with ${field} '${value}' retrieved successfully.`, data: result };
} else {
return { success: false, message: `No data found for ${field} '${value}'.` };
}
} catch (error) {
return { success: false, message: `Error retrieving data: ${error.message}` };
}
}
function runtimeMemoryDispatcher({ operation, key, value }) {
if (!key) {
return { success: false, message: "Missing key argument." };
}
switch (operation) {
case 'set':
if (value === undefined) {
return { success: false, message: "Missing value for 'set' operation." };
}
return runtimeMemoryStorage.set(key, value);
case 'get':
return runtimeMemoryStorage.get(key);
case 'del':
return runtimeMemoryStorage.del(key);
default:
return { success: false, message: "Invalid operation specified." };
}
}
async function dynamicContentDispatcher(operationData) {
const endpoint = 'http://localhost:3000'; // Base URL of your server
const headers = { 'Content-Type': 'application/json' };
// Validate operationData
if (!operationData || !Object.keys(operationData).length) {
return { success: false, message: "No operation specified." };
}
const operation = Object.keys(operationData)[0];
const params = operationData[operation];
try {
let response;
switch (operation) {
case 'add_element':
if (!params.id || params.content === undefined) {
return { success: false, message: "Missing 'id' or 'content' required for operation." };
}
response = await fetch(`${endpoint}/element`, {
method: 'POST',
headers: headers,
body: JSON.stringify({ id: params.id, content: params.content })
});
break;
case 'update_element':
if (!params.id || params.content === undefined) {
return { success: false, message: "Missing 'id' or 'content' required for operation." };
}
response = await fetch(`${endpoint}/element/${params.id}`, {
method: 'PUT',
headers: headers,
body: JSON.stringify({ content: params.content })
});
break;
case 'delete_element':
if (!params.id) {
return { success: false, message: "Missing 'id' required for deletion." };
}
response = await fetch(`${endpoint}/element/${params.id}`, {
method: 'DELETE',
headers: headers
});
break;
case 'update_js':
case 'update_css':
if (params.content === undefined) {
return { success: false, message: "Missing 'content' required for updating JS or CSS." };
}
response = await fetch(`${endpoint}/${operation}`, {
method: 'POST',
headers: headers,
body: JSON.stringify({ content: params.content })
});
break;
/*
case 'revert_changes':
if (!params.commitHash) {
return { success: false, message: "Missing 'commitHash' required for reverting changes." };
}
response = await fetch(`${endpoint}/revert`, {
method: 'POST',
headers: headers,
body: JSON.stringify({ commitHash: params.commitHash })
});
break;
case 'commits':
const queryParams = new URLSearchParams();
// Filters: commitHash, author, since, until
Object.entries(params.filters).forEach(([key, value]) => {
if (value) queryParams.append(key, value);
});
response = await fetch(`${endpoint}/commits?${queryParams.toString()}`, {
method: 'GET',
headers: headers
});
break;
case 'diffs':
if (!params.from || !params.to) {
return { success: false, message: "Both 'from' and 'to' are required for diff operation." };
}
const queryParamsDiff = new URLSearchParams();
queryParamsDiff.append('from', params.from);
queryParamsDiff.append('to', params.to);
response = await fetch(`${endpoint}/diffs?${queryParamsDiff.toString()}`, {
method: 'GET',
headers: headers
});
break;
*/
default:
return { success: false, message: "Invalid operation specified." };
}
// Check response status and parse JSON
if (response.ok) {
const data = await response.json();
return { success: true, data };
} else {
console.error(response, response.json());
return { success: false, message: `Server responded with status: ${response.status}` };
}
} catch (error) {
console.error('Error with API request:', error);
return { success: false, message: "Failed to execute API request.", error };
}
}
async function gitOperationsDispatcher(operationData) {
const endpoint = 'http://localhost:3000/api'; // Base URL of your server
const headers = { 'Content-Type': 'application/json' };
// Validate operationData
if (!operationData || !Object.keys(operationData).length) {
return { success: false, message: "No operation specified." };
}
const operation = Object.keys(operationData)[0];
const params = operationData[operation];
try {
let response = {status: 0, ok: false};
switch (operation) {
case 'git_add':
const queryParamsAdd = new URLSearchParams();
if (Array.isArray(params.files)) {
// If params.files is an array, append each file to the query string
params.files.forEach(file => {
queryParamsAdd.append('files', file);
});
} else if (typeof params.files === 'string') {
// If params.files is a single string, just append it
queryParamsAdd.append('files', params.files || '.');
}
const queryStringAdd = queryParamsAdd.toString();
response = await fetch(`${endpoint}/add?${queryStringAdd}`, {
method: 'GET',
headers: headers
});
break;
case 'git_commits':
if (params.list) {
const queryParamsCommitsList = {
...(params.list.commitHash && { commitHash: params.list.commitHash }),
...(params.list.author && { author: params.list.author }),
...(params.list.since && { since: params.list.since }),
...(params.list.until && { until: params.list.until })
};
response = await fetch(`${endpoint}/commits?${queryParamsCommitsList.toString()}`, {
method: 'GET',
headers: headers
});
} else if (params.create) {
const queryParamsCommitsCreate = {
...(params.create.message && { message: params.create.message }),
...(params.create.files && { files: params.create.files })
};
response = await fetch(`${endpoint}/commit`, {
method: 'POST',
headers: headers,
body: JSON.stringify(queryParamsCommitsCreate)
});
} else if (params.amend) {
response = await fetch(`${endpoint}/commit/${params.amend.commitHash}`, {
method: 'PATCH',
headers: headers,
body: JSON.stringify({ message: params.amend.message })
});
} else if (params.message) {
response = await fetch(`${endpoint}/commit`, {
method: 'POST',
headers: headers,
body: JSON.stringify({ message: params.message })
});
} else if (params.revert) {
response = await fetch(`${endpoint}/commit/${params.revert.commitHash}`, {
method: 'DELETE',
headers: headers
});
}
break;
case 'git_log':
const queryParams = new URLSearchParams(params);
response = await fetch(`${endpoint}/commits?${queryParams.toString()}`, {
method: 'GET',
headers: headers
});
break;
case 'git_branches':
if (params.list || !params) {
response = await fetch(`${endpoint}/branches`, {
method: 'GET',
headers: headers
});
} else if (params.create) {
response = await fetch(`${endpoint}/branches`, {
method: 'POST',
headers: headers,
body: JSON.stringify(params.create)
});
} else if (params.delete) {
response = await fetch(`${endpoint}/branches/${params.delete.branchName}`, {
method: 'DELETE',
headers: headers
});
}
break;
case 'git_tags':
if (params.list || !params) {
response = await fetch(`${endpoint}/tags`, {
method: 'GET',
headers: headers
});
} else if (params.create) {
response = await fetch(`${endpoint}/tags`, {
method: 'POST',
headers: headers,
body: JSON.stringify(params.create)
});
} else if (params.delete) {
response = await fetch(`${endpoint}/tags/${params.delete.tagName}`, {
method: 'DELETE',
headers: headers
});
}
break;
case 'git_diff':
const queryParamsDiff = {
...(params.from && { from: params.from }),
...(params.to && { to: params.to }),
...(params.file && { file: params.file })
};
response = await fetch(`${endpoint}/diffs?${queryParamsDiff.toString()}`, {
method: 'GET',
headers: headers
});
break;
case 'git_status':
response = await fetch(`${endpoint}/status`, {
method: 'GET',
headers: headers
});
break;
case 'git_stash':
if (params.list) {
response = await fetch(`${endpoint}/stash`, {
method: 'GET',
headers: headers
});
} else if (params.create) {
response = await fetch(`${endpoint}/stash`, {
method: 'POST',
headers: headers,
body: JSON.stringify({ message: params.create.message })
});
} else if (params.apply) {
response = await fetch(`${endpoint}/stash/apply`, {
method: 'POST',
headers: headers,
body: JSON.stringify({ stashId: params.apply.stashId })
});
} else if (params.delete) {
response = await fetch(`${endpoint}/stash/${params.delete.stashId}`, {
method: 'DELETE',
headers: headers
});
}
break;
case 'git_merge':
response = await fetch(`${endpoint}/merge`, {
method: 'POST',
headers: headers,
body: JSON.stringify({ branch: params.branch })
});
break;
case 'git_rebase':
response = await fetch(`${endpoint}/rebase`, {
method: 'POST',
headers: headers,
body: JSON.stringify({ branch: params.branch })
});
break;
case 'git_remote_operations':
const subOperation = Object.keys(params)[0]; // clone, fetch, pull, push
response = await fetch(`${endpoint}/${subOperation}`, {
method: 'POST',
headers: headers,
body: JSON.stringify(params[subOperation])
});
break;
default:
return { success: false, message: "Invalid operation specified." };
}
// Check response status and parse JSON
if (response.ok) {
const data = await response.json();
return { success: true, data };
} else {
console.error(response);
return { success: false, message: `Server responded with status: ${response.status}` };
}
} catch (error) {
console.error('Error with API request:', error);
return { success: false, message: "Failed to execute API request.", error };
}
}
function updateProgressBar(modelName, completed, total, startTime) {
const elapsedTime = ((performance.now() - startTime) / 1000).toFixed(2);
const percentage = Math.floor((completed / total) * 100);
const progressBar = "=".repeat((percentage / 10)) + " ".repeat(10 - (percentage / 10));
let processing = "";
if (modelName === "STARTING..." || modelName === "FINISHED!") {
processing = `${modelName}`;
} else {
processing = `Processing: ${modelName}`;
}
process.stdout.write(`\r Progress: [${progressBar}] ${percentage}% ${completed}/${total} - ${processing} - Time: ${elapsedTime}s`);
process.stdout.clearScreenDown();
}
async function askMultipleModels({ agents, prompt, supervisor }) {
// Check that prompt is given
if (!prompt) {
return { success: false, message: "No prompt specified." };
}
// Check that agents and supervisor have client and model arguments given and that they are valid
if (!agents || !Array.isArray(agents) || !agents.length) {
return { success: false, message: "No agents specified." };
}
// Check that all agents have client and model given
for (const agent of agents) {
if (!agent.client || !agent.model) {
return { success: false, message: "All agents must have client and model specified." };
}
}
if (supervisor && (!supervisor.client || !supervisor.model)) {
return { success: false, message: "Supervisor agent must have client and model specified." };
}
// Check that all agents have valid clients
const validClients = ["groq", "ollama", "anthropic", "openai"];
for (const agent of agents) {
if (!validClients.includes(agent.client)) {
return { success: false, message: `Invalid client specified for agent: ${agent.client}` };
}
}
// Check that supervisor has a valid client
if (supervisor && !validClients.includes(supervisor.client)) {
return { success: false, message: `Invalid client specified for supervisor: ${supervisor.client}` };
}
// Check that all agents have valid models
const validModels = {
"groq": groqModelNames,
"ollama": await getOllamaModelNames(),
"anthropic": anthropicModelNames,
"openai": openAIModelNames
};
for (const agent of agents) {
if (!validModels[agent.client].includes(agent.model)) {
return { success: false, message: `Invalid model specified for agent: ${agent.model}. Valid models are: ${validModels[agent.client].join(", ")}` };
}
}
// Check that supervisor has a valid model
if (supervisor && !validModels[supervisor.client].includes(supervisor.model)) {
return { success: false, message: `Invalid model specified for supervisor: ${supervisor.model}. Valid models are: ${validModels[supervisor.client].join(", ")}` };
}
try {
// Make sure the response log directory exists
if (!fs.existsSync(agentsResponsesDir)) {
fs.mkdirSync(agentsResponsesDir, { recursive: true });
}
const startTime = performance.now();
let completedAgents = 0;
const totalAgents = agents.length + 1; // Including supervisor as the final step
updateProgressBar("STARTING...", completedAgents, totalAgents, startTime);
// Define the agents requests function
const agentPromises = agents.map(async agent => {
try {
updateProgressBar(agent.model, completedAgents, totalAgents, startTime);
completedAgents++;
const agentSystemPrompt = getPrompt("agentSystemPrompt", agent.client, agent.model);
const agentResponse = await agentRequest(prompt, agent.client, agent.model, agentSystemPrompt);
await saveAgentResponseToFile(agent, agentResponse);
return { agent, response: agentResponse };
} catch (error) {
return { agent, response: { success: false, message: error.message } };
}
});
// Wait that all responses have been retrieved
const agentResponses = await Promise.all(agentPromises);
let supervisorSystemPrompt = getPrompt("supervisorSystemPrompt", supervisor.client, supervisor.model);
supervisorSystemPrompt = supervisorSystemPrompt.replace("<<original_prompt>>", prompt);
let supervisorPrompt = getPrompt("supervisorAgentsPrompt", supervisor.client, supervisor.model);
supervisorPrompt = supervisorPrompt.replace("<<responses>>", agentResponses.map(({ agent, response }) => `${agent.client}:${agent.model} - ${response.text}\n`).join("\n"));
updateProgressBar(supervisor.model, completedAgents, totalAgents, startTime);
completedAgents++;
const supervisorResponse = await agentRequest(supervisorPrompt, supervisor.client, supervisor.model, supervisorSystemPrompt);
await saveAgentResponseToFile(supervisor, supervisorResponse);
updateProgressBar("FINISHED!", completedAgents, totalAgents, startTime);
// Output answer as orange text terminal notation
console.log(`\n\n\r Supervisor (${supervisor.client}:${supervisor.model}) response:`, supervisorResponse.text);
return { success: true, message: supervisorResponse.text };
} catch (error) {
console.error('Error with API request:', error);
return { success: false, message: "Failed to execute API request.", error };
}
}
const functionToolCallbacks = {
"hangman": hangman,
"nodejs_code_runner": nodeCodeRunner,
"number_guessing": numberGuessing,