-
Notifications
You must be signed in to change notification settings - Fork 58
/
server.js
2540 lines (2122 loc) · 91.4 KB
/
server.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
// importing required node packages
let isShuttingDown = false;
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const basicAuth = require('express-basic-auth');
const fs = require('fs');
const { marked } = require('marked');
const app = express();
const bodyParser = require('body-parser');
// Increase the limit for JSON bodies
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true, parameterLimit: 50000 }));
app.use(express.json()); // for parsing application/json
app.use(express.static('public')); // Serves your static files from 'public' directory
const download = require('image-downloader');
const cors = require('cors');
app.use(cors());
const router = express.Router();
const { v4: uuidv4 } = require('uuid');
let temperature = process.env.TEMPERATURE ? parseFloat(process.env.TEMPERATURE) : 1;
console.log(`The current temperature is: ${temperature}`);
// openai
/*
const OpenAI = require('openai').default;
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY // This is also the default, can be omitted
});
*/
const OpenAI = require('openai').default;
// Check if the OPENAI_API_KEY environment variable is set
const apiKey = process.env.OPENAI_API_KEY;
let openai; // Declare openai outside the conditional block
if (!apiKey) {
console.warn("Warning: The OPENAI_API_KEY environment variable is missing. OpenAI features will be disabled.");
} else {
// Initialize OpenAI only if the API key is present
openai = new OpenAI({
apiKey: apiKey
});
}
// integrate google gemini
const { GoogleGenerativeAI } = require('@google/generative-ai');
const genAI = new GoogleGenerativeAI(process.env.GOOGLE_API_KEY);
const googleGenerativeAI = require("@google/generative-ai");
const HarmBlockThreshold = googleGenerativeAI.HarmBlockThreshold;
const HarmCategory = googleGenerativeAI.HarmCategory;
// Authenticates your login
// Basic Authentication users
const username = process.env.USER_USERNAME;
const password = process.env.USER_PASSWORD;
if (username && password) {
const users = {
[username]: password
};
// Apply basic authentication middleware
app.use(basicAuth({
users: users,
challenge: true
}));
// Allow access to the '/portal' route
app.get('/portal', (req, res) => {
res.sendFile('portal.html', { root: 'public' });
});
// Redirect all other routes (except for '/config' and '/setup') to '/portal'
app.get('*', (req, res, next) => {
if (req.path !== '/setup') {
next();
} else {
res.redirect('/portal');
}
});
} else {
// Redirect to the setup page if username and password are not set
app.get('*', (req, res, next) => {
if (req.path !== '/portal') {
next();
} else {
res.redirect('/setup');
}
});
}
app.get('/setup', (req, res) => {
res.sendFile('setup.html', { root: 'public' });
});
app.post('/setup', (req, res) => {
const { username, password, openaiApiKey, claudeApiKey, googleApiKey, mistralApiKey, qroqApiKey, openrouterApiKey, codestralApiKey } = req.body;
let envContent = `USER_USERNAME=${username}\nUSER_PASSWORD=${password}\n`;
if (openaiApiKey) {
envContent += `OPENAI_API_KEY=${openaiApiKey}\n`;
}
if (claudeApiKey) {
envContent += `CLAUDE_API_KEY=${claudeApiKey}\n`;
}
if (googleApiKey) {
envContent += `GOOGLE_API_KEY=${googleApiKey}\n`;
}
if (mistralApiKey) {
envContent += `MISTRAL_API_KEY=${mistralApiKey}\n`;
}
if (qroqApiKey) {
envContent += `QROQ_API_KEY=${qroqApiKey}\n`;
}
if (openrouterApiKey) {
envContent += `OPENROUTER_API_KEY=${openrouterApiKey}\n`;
}
if (codestralApiKey) {
envContent += `CODESTRAL_API_KEY=${codestralApiKey}\n`;
}
fs.writeFileSync('.env', envContent);
res.json({ message: 'Environment variables successfully written' });
// Allow access to the '/portal' route
app.get('/portal', (req, res) => {
res.sendFile('portal.html', { root: 'public' });
});
// Redirect all other routes (except for '/config' and '/setup') to '/portal'
app.get('*', (req, res, next) => {
if (req.path === '/portal' || req.path === '/config' || req.path === '/model') {
next();
} else {
res.redirect('/portal');
}
});
});
app.get('/get-env', (req, res) => {
const envContent = fs.readFileSync('.env', 'utf-8');
res.send(envContent);
});
app.post('/update-env', (req, res) => {
const newEnvContent = req.body.envContent;
fs.writeFileSync('.env', newEnvContent);
res.send('Environment variables updated successfully.');
});
// Endpoint to restart the server
app.post('/restart-server', (req, res) => {
/*
fs.appendFile('.env.example', '\nRESTART=TRUE', (err) => {
if (err) {
console.error('Failed to write to .env.example:', err);
return res.status(500).send('Failed to write to .env.example');
}
res.send('Server is restarting...');
});
*/
server.close(() => {
console.log("Server successfully shut down.");
process.exit(0);
}, 100); // 1-second delay
});
// Serve uploaded files from the 'public/uploads' directory
app.get('/uploads/:filename', (req, res) => {
const filename = req.params.filename;
res.sendFile(filename, { root: 'public/uploads' });
});
app.use('/uploads', express.static('public/uploads'));
// image uploads
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads');
},
filename: function (req, file, cb) {
let uploadPath = 'public/uploads/';
let originalName = file.originalname;
let fileExt = path.extname(originalName);
let baseName = path.basename(originalName, fileExt);
let finalName = originalName;
let counter = 1;
while (fs.existsSync(path.join(uploadPath, finalName))) {
finalName = `${baseName}(${counter})${fileExt}`;
counter++;
}
cb(null, finalName); // Use a modified file name if the original exists
}
});
const upload = multer({ storage: storage });
const FormData = require('form-data');
const path = require('path');
// transcribing audio with Whisper api
app.post('/transcribe', upload.single('audio'), async (req, res) => {
let transcription = "";
try {
// Use the direct path of the uploaded file
const uploadedFilePath = req.file.path;
// Create FormData and append the uploaded file
const formData = new FormData();
formData.append('file', fs.createReadStream(uploadedFilePath), req.file.filename);
let transcriptionResponse;
if (process.env.QROQ_API_KEY) {
formData.append('model', 'whisper-large-v3');
// API request
transcriptionResponse = await axios.post(
'https://api.groq.com/openai/v1/audio/transcriptions',
formData,
{
headers: {
...formData.getHeaders(),
'Authorization': `Bearer ${process.env.QROQ_API_KEY}`
}
}
);
} else {
formData.append('model', 'whisper-1');
// API request
transcriptionResponse = await axios.post(
'https://api.openai.com/v1/audio/transcriptions',
formData,
{
headers: {
...formData.getHeaders(),
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
}
}
);
}
// Cleanup: delete the temporary file
fs.unlinkSync(uploadedFilePath);
// Prepend "Voice Transcription: " to the transcription
transcription = "Voice Transcription: " + transcriptionResponse.data.text;
// Send the modified transcription back to the client
res.json({ text: transcription });
// Reset the transcription variable for future use
transcription = ""; // Reset to empty string
} catch (error) {
console.error('Error transcribing audio:', error.message);
res.status(500).json({ error: "Error transcribing audio", details: error.message });
}
});
// function to run text to speech api
app.post('/tts', async (req, res) => {
try {
const { text } = req.body;
// Call the OpenAI TTS API
const ttsResponse = await axios.post(
'https://api.openai.com/v1/audio/speech',
{ model: "tts-1-hd", voice: "echo", input: text },
{ headers: { 'Authorization': `Bearer ${process.env.OPENAI_API_KEY}` }, responseType: 'arraybuffer' }
);
// Send the audio file back to the client
res.set('Content-Type', 'audio/mpeg');
res.send(ttsResponse.data);
} catch (error) {
console.error('Error generating speech:', error.message);
res.status(500).json({ error: "Error generating speech", details: error.message });
}
});
// END
// image generation
// Endpoint for handling image generation requests
app.post('/generate-image', async (req, res) => {
const prompt = req.body.prompt;
try {
// Call to DALL·E API with the prompt
const dalResponse = await axios.post('https://api.openai.com/v1/images/generations', {
prompt: prompt,
model: "dall-e-3",
n: 1,
quality: 'hd',
response_format: 'url',
size: '1024x1024'
}, {
headers: {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
}
});
// Extract the image URL from the response
const imageUrl = dalResponse.data.data[0].url;
// Define a path to save the image
const uploadsDir = path.join(__dirname, 'public/uploads');
const imagePath = path.join(uploadsDir, `generated-${Date.now()}.jpg`);
// Ensure uploads directory exists
if (!fs.existsSync(uploadsDir)){
fs.mkdirSync(uploadsDir, { recursive: true });
}
// Download and save the image
try {
await download.image({ url: imageUrl, dest: imagePath });
res.json({ imageUrl: imageUrl });
} catch (error) {
console.error('Error saving image:', error);
res.status(500).json({ error: "Error saving image", details: error.message });
}
} catch (error) {
console.error('Error calling DALL·E API:', error.message);
res.status(500).json({ error: "Error calling DALL·E API", details: error.message });
}
});
// custom instructions read
let continueConv = false;
let chosenChat = '';
let summariesOnly = true; // Default to summaries only
let customPrompt = false;
let chosenPrompt = '';
// Endpoint to list available prompts
app.get('/listPrompts', async (req, res) => {
try {
const promptDir = path.join(__dirname, 'public', 'uploads', 'prompts');
const files = fs.readdirSync(promptDir);
const markdownFiles = files.filter(file => file.endsWith('.md'));
const promptInfo = {};
for (const file of markdownFiles) {
const content = fs.readFileSync(path.join(promptDir, file), 'utf8');
const nameMatch = content.match(/## \*\*(.*?)\*\*/);
const descriptionMatch = content.match(/### Description\s*\n\s*\*(.*?)\./s);
promptInfo[file.replace('.md', '')] = {
name: nameMatch ? nameMatch[1].trim() : file.replace('.md', ''),
description: descriptionMatch ? descriptionMatch[1].trim() : 'No description available'
};
}
res.json({ files: markdownFiles, promptInfo });
} catch (error) {
console.error('Error reading prompt directory:', error);
res.status(500).json({ error: 'Error reading prompt directory' });
}
});
// Endpoint to get a specific prompt's details
app.post('/setPrompt', async (req, res) => {
const { chosenPrompt } = req.body;
const promptFile = path.join(__dirname, 'public', 'uploads', 'prompts', `${chosenPrompt}.md`);
try {
const data = fs.readFileSync(promptFile, 'utf8');
const promptData = parsePromptMarkdown(data);
res.json({ prompt: promptData });
} catch (error) {
console.error('Error reading prompt file:', error);
res.status(500).json({ error: 'Error reading prompt file' });
}
});
let promptName;
// Endpoint to handle copying the prompt
app.post('/copyPrompt', async (req, res) => {
try {
const { chosenPrompt } = req.body;
customPrompt = true;
promptName = chosenPrompt;
instructions = await readInstructionsFile();
// Here you can implement any additional logic to handle the copied prompt
// For example, you might want to save it to a different file or update a database
res.json({ success: true, instructions });
} catch (error) {
console.error('Error copying prompt:', error);
res.status(500).json({ error: 'Error copying prompt' });
}
});
// Function to parse prompt markdown file
function parsePromptMarkdown(content) {
console.log(content);
const nameMatch = content.match(/## \*\*(.*?)\*\*/);
const descriptionMatch = content.match(/### Description\s*\n\s*\*(.*?)\*/s);
const bodyMatch = content.match(/#### Instructions\s*\n(.*?)\n##### Conversation starters/s);
return {
name: nameMatch ? nameMatch[1].trim() : 'No name found',
description: descriptionMatch ? descriptionMatch[1].trim() : 'No description available',
body: bodyMatch ? bodyMatch[1].trim() : 'No instructions available'
};
}
/*
// Endpoint to handle copying the prompt
app.post('/copyPrompt', async (req, res) => {
try {
customPrompt = true;
// call to read instructions file, inside custom prompt being true
// send the name of that file so that it can read it
// or just use the body text directlt?
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: 'Error copying prompt' });
}
});
*/
let conversationHistory = [];
let o1History = [];
let instructions;
// Function to read instructions from the file using fs promises
async function readInstructionsFile() {
try {
// Adjust the path if your folder structure is different
if (customPrompt) {
// file path goes to the the prompt file name we get from that separate async function
// sets instructions equal to the contents of that file
// instructions = await fs.promises.readFile(promptFile, 'utf8');
const promptFile = path.join(__dirname, 'public', 'uploads', 'prompts', `${promptName}.md`);
const content = fs.readFileSync(promptFile, 'utf8');
const parsedContent = parsePromptMarkdown(content);
return parsedContent.body;
} else {
instructions = await fs.promises.readFile('./public/instructions.md', 'utf8');
}
return instructions;
} catch (error) {
console.error('Error reading instructions file:', error);
return ''; // Return empty string or handle error as needed
}
}
// Function to initialize the conversation history with instructions
// giving the model a system prompt and adding tp
async function initializeConversationHistory() {
const fileInstructions = await readInstructionsFile();
systemMessage = `You are a helpful and intelligent AI assistant, knowledgeable about a wide range of topics and highly capable of a great many tasks.\n Specifically:\n ${fileInstructions}`;
if (continueConv) {
console.log("continue conversation", continueConv);
if (summariesOnly) {
console.log("summaries only", summariesOnly);
const contextAndSummary = await continueConversation(chosenChat);
systemMessage += `\n---\n${contextAndSummary}`;
} else {
systemMessage = await continueConversation(chosenChat);
}
}
conversationHistory.push({ role: "system", content: systemMessage });
return systemMessage;
}
// Call this function when the server starts
async function initializeSystem() {
const systemMessage = await initializeConversationHistory();
// Make sure this systemMessage is passed where needed
// Continue with the rest of your initialization logic
}
let geminiHistory = '';
async function readGeminiFile() {
try {
// Adjust the path if your folder structure is different
const geminiFile = await fs.promises.readFile('./public/uploads/geminiMessage.txt', 'utf8');
return geminiFile;
} catch (error) {
console.error('Error reading instructions file:', error);
return ''; // Return empty string or handle error as needed
}
}
// Function to initialize the Gemini conversation history with system message
async function initializeGeminiConversationHistory() {
try {
const geminiMessage = await readGeminiFile();
let systemMessage = 'System Prompt: ' + geminiMessage;
if (continueConv) {
if (summariesOnly) {
const contextAndSummary = await continueConversation(chosenChat);
systemMessage += `\n---\n${contextAndSummary}`;
} else {
systemMessage = await continueConversation(chosenChat);
}
}
geminiHistory += systemMessage + '\n';
} catch (error) {
console.error('Error initializing Gemini conversation history:', error);
}
}
// Call this function when the server starts
// Async function to continue conversation by loading chat context and summary
async function continueConversation(chosenChat) {
try {
// Read the chosen chat file
const conversationFile = await fs.promises.readFile(path.join(__dirname, 'public/uploads/chats', `${chosenChat}.txt`), 'utf8');
if (summariesOnly) {
// Regex to extract everything starting from CONTEXT
const regex = /\n\n-----\n\n(.+)/s;
const match = conversationFile.match(regex);
if (match && match[1]) {
const contextAndSummary = match[1];
return contextAndSummary;
} else {
throw new Error('Context and summary not found in the conversation file.');
}
} else {
console.log("summaries only", summariesOnly);
return conversationFile
}
} catch (error) {
console.error('Error in continueConversation:', error);
throw error;
}
}
// Endpoint to receive chosen chat info from the frontend
app.post('/setChat', async (req, res) => {
try {
// Extract chosen chat info from request body
chosenChat = req.body.chosenChat;
// Set continueConv to true
continueConv = true;
// Optionally call continueConversation to verify functionality
const contextAndSummary = await continueConversation(chosenChat);
console.log('Context and Summary:', contextAndSummary);
// Send response back to frontend
res.status(200).json({ message: 'Chat set successfully', chosenChat });
} catch (error) {
console.error('Error in /setChat endpoint:', error);
res.status(500).json({ message: 'Failed to set chat', error: error.message });
}
});
// Endpoint to list chat files
app.get('/listChats', (req, res) => {
const folderPath = path.join(__dirname, 'public/uploads/chats');
fs.readdir(folderPath, (err, files) => {
if (err) {
console.error('Error reading chat files:', err);
res.status(500).json({ message: 'Failed to list chat files', error: err.message });
return;
}
const sortedFiles = files.sort((a, b) => fs.statSync(path.join(folderPath, b)).mtime - fs.statSync(path.join(folderPath, a)).mtime);
res.status(200).json({ files: sortedFiles });
});
});
// Endpoint to get chat summary
app.get('/getSummary/:chatName', async (req, res) => {
try {
const chatName = req.params.chatName;
const conversationFile = await fs.promises.readFile(path.join(__dirname, 'public/uploads/chats', `${chatName}.txt`), 'utf8');
const regex = /Conversation Summary: (.+)/s;
const match = conversationFile.match(regex);
if (match && match[1]) {
const summary = match[1].split('\n\n')[0];
res.status(200).json({ summary });
} else {
res.status(404).json({ message: 'Summary not found in the conversation file.' });
}
} catch (error) {
console.error('Error in /getSummary endpoint:', error);
res.status(500).json({ message: 'Failed to get summary', error: error.message });
}
});
// Endpoint to set summaries only
app.post('/setSummariesOnly', (req, res) => {
try {
summariesOnly = req.body.summariesOnly;
console.log(summariesOnly);
res.status(200).json({ message: 'Summaries only setting updated successfully', summariesOnly });
} catch (error) {
console.error('Error in /setSummariesOnly endpoint:', error);
res.status(500).json({ message: 'Failed to update summaries only setting', error: error.message });
}
});
// Function to convert conversation history to HTML
async function exportChatToHTML() {
// Log the current state of both conversation histories before deciding which one to use
// console.log("Current GPT Conversation History: ", JSON.stringify(conversationHistory, null, 2));
// console.log("Current Claude Conversation History: ", JSON.stringify(claudeHistory, null, 2));
let containsAssistantMessage = conversationHistory.some(entry => entry.role === 'assistant');
let chatHistory;
let isClaudeChat = false;
if (o1History.length > 0) {
console.log("Using O1 conversation history because it's non-empty.");
chatHistory = o1History;
} else if (containsAssistantMessage && conversationHistory.length > 0) {
console.log("Using GPT conversation history because it's non-empty.");
chatHistory = conversationHistory;
} else {
console.log("Using Claude conversation history as GPT history is empty or undefined.");
chatHistory = [...claudeHistory];
chatHistory.unshift({
role: 'system',
content: claudeInstructions
});
isClaudeChat = true;
}
// Log the determined chatHistory
// console.log("Determined Chat History: ", JSON.stringify(chatHistory, null, 2));
console.log("Chat History: ", JSON.stringify(chatHistory, null, 2));
// console.log(savedHistory);
chatType = 'chat';
const tokens = await tokenizeHistory(chatHistory, modelID, chatType);
// console.log("Total Tokens: ", tokens);
const cost = await calculateCost(tokens, modelID);
console.log("Total Cost: ", cost);
if (isClaudeChat) {
console.log("Redefining the system prompt for html.");
chatHistory = [...claudeHistory];
chatHistory.unshift({
role: 'system',
content: 'Claude AI: You are a helpful and intelligent AI assistant, knowledgeable about a wide range of topics and highly capable of a great many tasks.'
});
}
// Convert chat history to a string for title generation
const savedHistory = chatHistory.map(entry => {
let formattedEntry = '';
if (entry.role === 'system') {
formattedEntry = `System: \n${entry.content}\n`;
} else if (entry.role === 'user' || entry.role === 'assistant') {
const role = entry.role.charAt(0).toUpperCase() + entry.role.slice(1);
if (Array.isArray(entry.content)) {
formattedEntry = `${role}: ${entry.content.map(item => {
if (item.type === 'text') {
return item.text;
} else if (item.type === 'image_url') {
return `[Image: ${item.image_url.url}]`;
}
return '';
}).join(' ')}\n`;
} else if (typeof entry.content === 'string') {
formattedEntry = `${role}: \n${entry.content}\n`;
}
}
return formattedEntry;
}).join('\n');
// Generate title and save chat history
const { title, summary } = await titleChat(savedHistory, tokens, cost);
console.log(`Title: ${title}`);
console.log(`Summary: ${summary}`);
let htmlContent = `
<html>
<head>
<title>${title}</title>
<style>
body { font-family: Arial, sans-serif; }
.message { margin: 10px 0; padding: 10px; border-radius: 5px; }
.system { background-color: #f0f0f0; }
.user { background-color: #d1e8ff; }
.assistant { background-color: #c8e6c9; }
.generated-image { max-width: 100%; height: auto; }
.summary { background-color: #f9f9f9; padding: 10px; margin: 20px 0; border-radius: 5px; }
.summary h3 { margin-top: 0; }
</style>
</head>
<body>
`;
chatHistory.forEach(entry => {
let formattedContent = '';
if (entry.role === 'system' && typeof entry.content === 'string') {
// Format Claude's system prompt
formattedContent = `<pre>${entry.content.replace(/</g, '<').replace(/>/g, '>')}</pre>`;
} else if (Array.isArray(entry.content)) {
entry.content.forEach(item => {
if (item.type === 'text' && typeof item.text === 'string') {
formattedContent += marked(item.text); // Convert Markdown to HTML
} else if (item.type === 'image_url') {
formattedContent += `<img src="${item.image_url.url}" alt="User Uploaded Image" class="generated-image"/>`;
}
});
} else if (typeof entry.content === 'string') {
formattedContent = marked(entry.content); // Directly convert string content
} else {
console.error('Unexpected content type in conversationHistory:', entry.content);
}
htmlContent += `<div class="message ${entry.role}"><strong>${entry.role.toUpperCase()}:</strong> ${formattedContent}</div>`;
});
htmlContent += `
<div class="summary">
<h3>Summary</h3>
<p>Total Tokens: ${tokens.totalTokens}</p>
<p>Total Cost: ¢${cost.toFixed(6)}</p>
<p>Summary: ${summary}</p>
</div>
</body></html>`;
return htmlContent;
}
// Function to get a unique file name
function getUniqueFilePath(basePath, baseTitle) {
let counter = 1;
let fileName = `${baseTitle}.txt`;
let filePath = path.join(basePath, fileName);
// Keep checking until we find a filename that doesn't exist
while (fs.existsSync(filePath)) {
counter++;
fileName = `${baseTitle}-${counter}.txt`;
filePath = path.join(basePath, fileName);
}
return filePath;
}
let summary = '';
let maxLength = 200;
async function returnTitle(history) {
// Function to generate a title
async function generateTitle() {
const completion = await openai.chat.completions.create({
model: 'gpt-4o-mini',
temperature: 0.4,
max_tokens: 10,
messages: [
{ role: 'system', content: 'You will be given the contents of a conversation between a Human and an AI Assistant. Please title this chat by summarizing the topic of the conversation in under 5 plaintext words. Ignore the System Message and focus solely on the User-AI interaction. This will be the name of the file saved via Node, so keep it *extremely* short and concise! Examples: "Friendly AI Assistance", "Install Plex Media Server", "App Layout Feedback", "Calculating Indefinite Integrals", or "Total Cost Calculation", etc. The title should resemble a quick and easy reference point for the User to remember the conversation, and follow smart and short naming conventions. Do NOT use any special symbols; simply return the words in plaintext without any formatting, markdown, quotes, etc. The title needs to be compatible with a Node.js filename, so it needs to be short! Output should consist of a few words only, or there will be a ENAMETOOLONG error!.' },
{ role: 'user', content: history }
]
});
return completion.choices[0].message.content.trim().replace(/ /g, '_');
}
try {
title = await generateTitle();
if (title.length > maxLength) {
title = 'chat_history';
}
} catch (error) {
console.error("Error generating title:", error);
title = "chat_history";
}
return title;
}
async function titleChat(history, tokens, cost) {
/*
// Request to OpenAI to generate a title
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'system', content: 'You will be given the contents of a conversation between a Human and an AI Assistant. Please title this chat by summarizing the topic of the conversation in under 5 plaintext words. Ignore the System Message and focus solely on the User-AI interaction. This will be the name of the file saved via Node, so keep it *extremely* short and concise! Examples: "Friendly AI Assistance", "Install Plex Media Server", "App Layout Feedback", "Calculating Indefinite Integrals", or "Total Cost Calculation", etc. The title should resemble a quick and easy reference point for the User to remember the conversation, and follow smart and short naming conventions. Do NOT use any special symbols; simply return the words in plaintext without any formatting, markdown, quotes, etc. The title needs to be compatible with a Node.js filename, so it needs to be short! Output should consist of a few words only, or there will be a ENAMETOOLONG error!.' },
{ role: 'user', content: history }
]
});
*/
try {
const summaryCompletion = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [
{ role: 'system', content: 'You will be shown the contents of a conversation between a Human and an AI Assistant. Please summarize this chat in a brief paragraph consisting of no more than 4-6 sentences. Ignore the System Message and focus solely on the User-AI interaction. This description will be appended to the chat file for the user and AI to reference. Keep it extremely concise but thorough, shortly covering all important context necessary to retain.' },
{ role: 'user', content: history }
]
});
summary = summaryCompletion.choices[0].message.content;
} catch (error) {
console.error("Error generating summary:", error);
summary = "No summary could be generated.";
}
// Extract the title from the response
title = await returnTitle(history);
console.log("Generated Title: ", title);
const folderPath = path.join(__dirname, 'public/uploads/chats');
// Ensure the nested folder exists
fs.mkdirSync(folderPath, { recursive: true });
// Get a unique file path
const filePath = getUniqueFilePath(folderPath, title);
// Define the full file path
// const filePath = path.join(folderPath, `${title}.txt`);
let chatText;
chatText = `${history}\n---\nTotal Tokens: ${tokens.totalTokens}\nTotal Cost: ¢${cost.toFixed(6)}\n\n-----\n\nCONTEXT: Above, you may be shown a conversation between the User -- a Human -- and an AI Assistant (yourself). If not, a summary of said conversation is below for you to reference. INSTRUCTION: The User will send a message/prompt with the expectation that you will pick up where you left off and seamlessly continue the conversation. Do not give any indication that the conversation had paused or resumed; simply answer the User's next query in the context of the above Chat, inferring the Context and asking for additional information if necessary.\n---\nConversation Summary: ${summary}`;
/*
if (summariesOnly) {
console.log("summaries only ")
chatText = `${history}\n\nTotal Tokens: ${tokens.totalTokens}\nTotal Cost: $${cost.toFixed(6)}\n\n-----\n\nCONTEXT: Below is a summary of the conversation between the User -- a Human -- and an AI Assistant (yourself). INSTRUCTION: The User will send a message/prompt with the expectation that you will pick up where you left off and seamlessly continue the conversation. Do not give any indication that the conversation had paused or resumed; simply answer the User's next query in the context of the above Chat, inferring the Context and asking for additional information if necessary.\n---\nConversation Summary: ${summary}`;
} else {
chatText = `${history}\n---\nTotal Tokens: ${tokens.totalTokens}\nTotal Cost: $${cost.toFixed(6)}\n\n-----\n\nCONTEXT: Above, you may be shown a conversation between the User -- a Human -- and an AI Assistant (yourself). If not, summary of said conversation is below for you to reference. INSTRUCTION: The User will send a message/prompt with the expectation that you will pick up where you left off and seamlessly continue the conversation. Do not give any indication that the conversation had paused or resumed; simply answer the User's next query in the context of the above Chat, inferring the Context and asking for additional information if necessary.\n---\nConversation Summary: ${summary}`;
}
*/
fs.writeFileSync(filePath, chatText);
// test...
// const chatText = `${history}\n\nTotal Tokens: ${tokens.totalTokens}\nTotal Cost: $${cost.toFixed(6)}\n\n-----\n\nCONTEXT: Above may be the conversation between the User -- a Human -- and an AI Assistant (yourself); if you do not see it, the User has decided to display only a summary. The summary of said conversation is below for you to reference. INSTRUCTION: The User will send a message/prompt with the expectation that you will pick up where you left off and seamlessly continue the conversation. Do not give any indication that the conversation had paused or resumed; simply answer the User's next query in the context of the above Chat, inferring the Context and asking for additional information if necessary.\n---\nConversation Summary: ${summary}`;
// Save the chat history to a file with the generated title
console.log(`Chat history saved to ${filePath}`);
return { title, summary };
}
const { get_encoding, encoding_for_model } = require("tiktoken");
/**
* Tokenize chat history based on a specified model and type
* @param {string} history - The chat history as a string
* @param {string} model - The OpenAI model to use for encoding
* @param {string} type - The format type of the chat history (e.g., 'gemini')
* @returns {Promise<Object>} - An object containing the total tokens and tokens per segment
*/
async function tokenizeHistory(history, model, type) {
// Load the encoder for the specified model
const encoder = encoding_for_model(model);
// Function to split history into segments for 'gemini' format
function splitGeminiSegments(chatHistory) {
// Regex pattern to separate different parts of the conversation
const segmentRegex = /(?:System Prompt:|User Prompt:|Response:)([^:]+)(?=System Prompt:|User Prompt:|Response:|$)/g;
const matches = [];
let match;
while ((match = segmentRegex.exec(chatHistory)) !== null) {
matches.push(match[1].trim());
}
return matches.map((text, index) => ({
role: index % 3 === 0 ? 'System Prompt' : index % 3 === 1 ? 'User Prompt' : 'Response',
text
}));
}
// Function to split history into segments for 'assistant' format
function splitAssistantSegments(chatHistory) {
// Regex pattern to separate different parts of the conversation starting from SYSTEM
const segmentRegex = /(SYSTEM:|USER:|ASSISTANT:)(.*?)(?=(SYSTEM:|USER:|ASSISTANT:|$))/gs;
const matches = [];
let match;
while ((match = segmentRegex.exec(chatHistory)) !== null) {
matches.push({
role: match[1].replace(':', '').trim(),
text: match[2].trim()
});
}
return matches;
}
// Function to split history into segments for 'chat' format
function splitChatSegments(chatHistory) {
return chatHistory.map(entry => ({
role: entry.role.toUpperCase(),
text: Array.isArray(entry.content) ? entry.content.map(item => item.type === 'text' ? item.text : '').join(' ') : entry.content
}));
}
// Function to split history into segments based on the type
function splitSegments(chatHistory, type) {
if (type === 'gemini') {
return splitGeminiSegments(chatHistory);
} else if (type === 'assistant') {
return splitAssistantSegments(chatHistory);
} else if (type === 'chat') {
return splitChatSegments(chatHistory);
}
throw new Error(`Unknown history type: ${type}`);
}
// Split the chat history into segments
let segments;
try {
segments = splitSegments(history, type);
} catch (error) {
console.error(error.message);
encoder.free();
return;
}
// Calculate the number of tokens for each segment and the total
let totalTokens = 0;
const tokensPerSegment = segments.map(segment => {
const tokens = encoder.encode(segment.text);
totalTokens += tokens.length;
return {
role: segment.role,
text: segment.text,
tokens: tokens.length
};
});
// Free the encoder
encoder.free();
// console.log("Total Tokens: ", totalTokens);
// console.log("Tokens Per Segment: ", tokensPerSegment);
return {
totalTokens,
tokensPerSegment
};
}
/**
* Calculate the total cost of a conversation based on token counts, model pricing, and role
* @param {Object} tokens - Object containing totalTokens and tokensPerSegment
* @param {string} model - String identifying the OpenAI or Claude model
* @returns {Promise<number>} - Total cost of the conversation
*/
async function calculateCost(tokens, model) {
let totalCost = 0;
let cumulativeInputTokens = 0;
// Define pricing based on model
let inputCostPerMillion, outputCostPerMillion;
if (model === 'gpt-4') {
inputCostPerMillion = 30.00;
outputCostPerMillion = 60.00;
} else if (model === 'gpt-4-turbo') {
inputCostPerMillion = 10.00;
outputCostPerMillion = 30.00;
} else if (model === 'gpt-4o') {
inputCostPerMillion = 5.00;
outputCostPerMillion = 15.00;
} else if (model === 'gpt-4o-mini') {