forked from Zaki-1052/GPTPortal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
1352 lines (1098 loc) · 44.8 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');
// openai
const OpenAI = require('openai').default;
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY // This is also the default, can be omitted
});
// 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;
const users = {
[username]: password
};
// Conditionally apply basic authentication middleware
if (process.env.DISABLE_AUTH !== 'true') {
// Apply basic authentication middleware only if authentication is enabled
app.use(basicAuth({
users: users,
challenge: true
}));
}
// 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);
formData.append('model', 'whisper-1');
// API request
const 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 conversationHistory = [];
// Function to read instructions from the file using fs promises
async function readInstructionsFile() {
try {
// Adjust the path if your folder structure is different
const 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}`;
conversationHistory.push({ role: "system", content: systemMessage });
return systemMessage;
}
// Call this function when the server starts
initializeConversationHistory();
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/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;
geminiHistory += systemMessage + '\n';
} catch (error) {
console.error('Error initializing Gemini conversation history:', error);
}
}
// Call this function when the server starts
initializeGeminiConversationHistory();
// Function to convert conversation history to HTML
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;
if (containsAssistantMessage) {
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: systemMessage
});
}
// Log the determined chatHistory
console.log("Determined Chat History: ", JSON.stringify(chatHistory, null, 2));
let htmlContent = `
<html>
<head>
<title>Chat History</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; }
/* Add more styles as needed for Markdown elements like headers, lists, etc. */
</style>
</head>
<body>
`;
console.log("Chat History: ", JSON.stringify(chatHistory, null, 2));
chatHistory.forEach(entry => {
let formattedContent = '';
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 += '</body></html>';
return htmlContent;
}
// Function to convert Gemini conversation history to HTML
function exportGeminiChatToHTML() {
let htmlContent = `
<html>
<head>
<title>Gemini Chat History</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; }
/* Additional styles */
</style>
</head>
<body>
`;
// Convert newlines in each part of the chat history to <br> for HTML display
const convertNewlinesToHtml = text => text.replace(/\n/g, '<br>');
// Use a regular expression to match the prompts and responses in the history
const messageRegex = /(System Prompt: |User Prompt: |Response: )/g;
// Split the history by the regex, but keep the delimiters
const messages = geminiHistory.split(messageRegex).slice(1); // slice to remove the first empty string if any
// Process the messages in pairs (label + content)
for (let i = 0; i < messages.length; i += 2) {
const label = messages[i];
const content = messages[i + 1];
let roleClass = '';
if (label === 'System Prompt: ') {
roleClass = 'system';
} else if (label === 'User Prompt: ') {
roleClass = 'user';
} else if (label === 'Response: ') {
roleClass = 'assistant';
}
htmlContent += `<div class="message ${roleClass}"><strong>${label.trim()}</strong> ${convertNewlinesToHtml(content.trim())}</div>`;
}
htmlContent += '</body></html>';
return htmlContent;
}
// file upload
let file_id;
let fileContents;
let embedding;
let isAssistants = false;
// Endpoint to handle image upload
app.post('/upload-file', upload.single('file'), async (req, res) => {
console.log("File received in /upload-file:", req.file);
if (!req.file) {
return res.status(400).send({ error: 'No image file provided.' });
}
const tempFilePath = req.file.path;
try {
if (isAssistants === false) {
file_id = req.file.filename;
fileContents = await fs.promises.readFile(tempFilePath, 'utf8');
console.log("File Contents:", fileContents);
console.log("File ID:", file_id);
console.log(fileContents);
// embedding = send to /embeddings python backend in FlaskApp
console.log("File ID:", file_id)
} else if (isAssistants === true) {
// Create a file for the assistants
if (!assistant) {
const systemMessage = await initializeConversationHistory();
await AssistantAndThread(modelID, systemMessage);
}
const file = await openai.files.create({
file: fs.createReadStream(tempFilePath),
purpose: 'assistants'
});
const assistantFile = await openai.beta.assistants.files.create(
assistant.id,
{
file_id: file.id
}
);
console.log("File attached to assistant:", assistantFile);
}
// Optional: Clean up the uploaded file after sending to OpenAI
fs.unlink(tempFilePath, (err) => {
if (err) console.error("Error deleting temp file:", err);
console.log("Temp file deleted");
});
initialize = false;
console.log("Initialize:", initialize)
res.json({ success: true, fileId: file_id, initialize });
} catch (error) {
console.error('Failed to upload file to OpenAI:', error);
}
});
// Assistant Handling
// At the top of server.js, after reading environment variables
const ASSISTANT_ID = process.env.ASSISTANT_ID || null;
const THREAD_ID = process.env.THREAD_ID || null;
let systemMessage; // Global variable for systemMessage
let assistant = null;
let thread = null;
let response = '';
let initialize = true;
let messages;
let modelID = 'gpt-4o';
// Utility function to ensure Assistant and Thread initialization
async function AssistantAndThread(modelID, systemMessage) {
// Conditional logic to either use provided IDs or create new instances
if (!assistant && ASSISTANT_ID) {
// Set the assistant using the ID from the environment
assistant = await openai.beta.assistants.retrieve(
ASSISTANT_ID
);
console.log("Using existing Assistant ID", assistant)
}
if (!thread && THREAD_ID) {
// Directly use the provided Thread ID without creating a new thread
thread = await openai.beta.threads.retrieve(
THREAD_ID
);
console.log("Using existing Thread ID from .env", thread);
} else if (!thread) {
// Only create a new thread if it's not provided and an assistant exists
// This could mean creating a new assistant if one wasn't provided
if (!assistant) {
assistant = await openai.beta.assistants.create({
name: "Assistant",
instructions: systemMessage,
tools: [{type: "file_search"}, {type: "code_interpreter"}],
model: modelID
});
console.log("Creating new Assistant:", assistant)
}
thread = await openai.beta.threads.create();
console.log("New Thread ensured:", thread);
}
}
// Function to handle message sending and responses
async function handleMessage(thread, assistant, userMessage) {
try {
let message = await openai.beta.threads.messages.create(thread.id, {
role: "user",
content: userMessage,
});
let run = await openai.beta.threads.runs.create(thread.id, {
assistant_id: assistant.id,
});
run = await openai.beta.threads.runs.retrieve(thread.id, run.id);
// Initialize runStatus variable
let runStatus;
// Poll for run completion
do {
runStatus = await openai.beta.threads.runs.retrieve(thread.id, run.id);
console.log("Run Status:", runStatus.status); // Debugging: Log the current run status
if(runStatus.status !== 'completed') {
// If the run is not completed, wait for a bit before checking the status again
await new Promise(resolve => setTimeout(resolve, 1000)); // 1 second delay
}
} while(runStatus.status !== 'completed');
// Once the run is completed, fetch the messages
messages = await openai.beta.threads.messages.list(thread.id);
// Sort messages by 'created_at' in descending order and then filter for the assistant's messages
const sortedAndFilteredMessages = messages.body.data
.sort((a, b) => b.created_at - a.created_at)
.filter(msg => msg.role === 'assistant');
if (sortedAndFilteredMessages.length > 0) {
// The first message in the array is now the latest one from the assistant
const latestAssistantMessage = sortedAndFilteredMessages[0];
const formattedResponse = latestAssistantMessage.content.map(content => {
// Assuming 'content.text' is the correct path to the message text.
// Adjust according to the actual structure of the 'content' array items
return typeof content.text === 'object' ? content.text.value : content.text;
}).join('\n');
let response = formattedResponse;
console.log("Response:", response);
return { text: response };
} else {
throw new Error('No assistant messages found in the thread.');
}
} catch (error) {
console.error("Error sending messages:", error);
throw error; // Rethrow the error for upstream handling
}
}
app.post('/assistant', async (req, res) => {
let userMessage = req.body.message;
modelID = req.body.modelID;
initialize = req.body.initialize;
isAssistants = true;
try {
// Check if assistant and thread need to be initialized
if (initialize === true) {
console.log("Initialize:", initialize)
const systemMessage = await initializeConversationHistory();
await AssistantAndThread(modelID, systemMessage);
response = await handleMessage(thread, assistant, userMessage);
console.log("Try Response:", response)
res.json({ text: response });
} else if (initialize === false) {
console.log("Initialize:", initialize)
console.log("Assistant and Thread already exist");
response = await handleMessage(thread, assistant, userMessage);
console.log("Try Response:", response)
res.json({ text: response });
}
} catch (error) {
console.error('Error in /assistant endpoint:', error.message);
res.status(500).json({ error: "An error occurred in the server.", details: error.message });
}
});
// END
// Assumes `thread` is available within this scope
async function fetchMessages() {
try {
const messagesResponse = await openai.beta.threads.messages.list(thread.id);
if (messagesResponse && messagesResponse.body && messagesResponse.body.data) {
return messagesResponse.body.data;
} else {
console.error("Failed to fetch messages or no messages available.");
return [];
}
} catch (error) {
console.error("Error fetching messages:", error);
return [];
}
}
// Helper function to convert markdown to HTML
const convertMarkdownToHtml = markdown => marked(markdown);
// Function to export conversation history to HTML, including systemMessage and ensuring correct order
async function exportAssistantsChat() {
let messages = await fetchMessages(); // Fetch messages using the new function
// Assuming messages are in reverse chronological order; sort them to chronological order
messages.sort((a, b) => a.created_at - b.created_at);
console.log("Messages Response:", JSON.stringify(messages, null, 2)); // Enhanced debugging: Log the messages response with formatting
const systemMessage = await initializeConversationHistory();
// Convert systemMessage from markdown to HTML and ensure it's only added if defined
const systemMessageHtml = systemMessage ? convertMarkdownToHtml(systemMessage) : '';
let htmlContent = `
<html>
<head>
<title>Chat History</title>
<style>
body { font-family: Arial, sans-serif; }
.message { margin: 10px 0; padding: 10px; border-radius: 5px; }
.system-message { background-color: #ffffcc; } /* Styling for system message */
.system { background-color: #f0f0f0; }
.user { background-color: #d1e8ff; }
.assistant { background-color: #c8e6c9; }
.generated-image { max-width: 100%; height: auto; }
</style>
</head>
<body>
${systemMessageHtml ? `<div class="message system-message"><strong>SYSTEM:</strong> ${systemMessageHtml}</div>` : ''}
`; // Conditionally prepend the systemMessage in HTML format to the chat history
messages.forEach(message => {
const roleClass = message.role;
let formattedContent = message.content.map(contentItem => {
if (contentItem.type === 'text') {
// Handle nested text object structure
const textContent = typeof contentItem.text === 'object' ? (contentItem.text.value || "") : contentItem.text;
return convertMarkdownToHtml(textContent);
} else if (contentItem.type === 'image') {
// Handle image content
return `<img src="${contentItem.image_url}" alt="Generated Image" class="generated-image"/>`;
}
}).filter(Boolean).join(''); // Filter out undefined or null values and join
htmlContent += `<div class="message ${roleClass}"><strong>${roleClass.toUpperCase()}:</strong> ${formattedContent}</div>`;
});
htmlContent += '</body></html>';
return htmlContent;
}
// Function to convert an image URL to base64
async function imageURLToBase64(url) {
try {
const response = await axios.get(url, {
responseType: 'arraybuffer' // Ensure the image data is received in the correct format
});
return `data:image/jpeg;base64,${Buffer.from(response.data).toString('base64')}`;
} catch (error) {
console.error('Error fetching image:', error);
return null; // Return null if there is an error
}
}
let imageName;
let uploadedImagePath;
// Endpoint to handle image upload
app.post('/upload-image', upload.single('image'), async (req, res) => {
console.log("File received in /upload-image:", req.file);
if (!req.file) {
return res.status(400).send({ error: 'No image file provided.' });
}
uploadedImagePath = req.file.path;
imageName = req.file.filename;
// Generate URL for the uploaded image
const imageUrl = `${req.protocol}://${req.get('host')}/uploads/${req.file.filename}`;
// Send the image URL back to the client
res.send({ imageUrl: imageUrl });
});
// Function to convert an image file to base64
function imageToBase64(filePath) {
const image = fs.readFileSync(filePath);
return `data:image/jpeg;base64,${image.toString('base64')}`;
}
// Google Gemini Endpoint
// Converts an image file directly to the format required by the Gemini model
function convertImageForGemini(filePath, mimeType) {
try {
// Validate input parameters
if (!filePath || !mimeType) {
throw new Error('Invalid arguments: filePath and mimeType are required');
}
// Read file and encode in base64
const fileData = fs.readFileSync(filePath);
const base64Data = fileData.toString('base64');
return {
inlineData: {
data: base64Data,
mimeType
},
};
} catch (error) {
console.error('Error in convertImageForGemini:', error.message);
return null;
}
}
// Gemini Safety settings reduced to none for each required category.
// Feel free to adjust, but be aware that the RLHP severely neuters the model.
const safetySettings = [
{
category: HarmCategory.HARM_CATEGORY_HARASSMENT,
threshold: HarmBlockThreshold.BLOCK_NONE,
},
{
category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold: HarmBlockThreshold.BLOCK_NONE,
},
{
category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
threshold: HarmBlockThreshold.BLOCK_NONE,
},
{
category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold: HarmBlockThreshold.BLOCK_NONE,
},
];
// Define a default configuration for generation parameters
// These are the settings for Gemini
const defaultConfig = {
candidate_count: 1, // How many responses the model gives
// stop_sequences: ["\n"], // Model stops generating at these
max_output_tokens: 2000, // Completion lengths
// top_p: 0.9,
// nucleus sampling, temperature alternative
// top_k: 40,
// random sampling
temperature: 1 // random sampling
};
// see my comments on the GPT API parameters for more explanations
// Docs: https://ai.google.dev/docs/concepts#model_parameters
app.post('/gemini', async (req, res) => {
try {
const { model, prompt, imageParts, history } = req.body;
console.log('Prompt: ', prompt)
isAssistants = false;
// Check for shutdown command
if (prompt === "Bye!") {
console.log("Shutdown message received. Exporting chat and closing server...");
// Export chat history to HTML
const htmlContent = exportGeminiChatToHTML();
// Set headers for file download
res.set('Content-Type', 'text/html');
res.set('Content-Disposition', 'attachment; filename="chat_history.html"');
// Send the HTML content
res.send(htmlContent);
// Wait for the response to be fully sent before shutting down
res.end(() => {
console.log("Chat history sent to client, initiating shutdown...");
if (isShuttingDown) {
return res.status(503).send('Server is shutting down');
}
isShuttingDown = true; // Set the shutdown flag
// Delay before shutting down the server to allow file download
setTimeout(() => {
server.close(() => {
console.log("Server successfully shut down.");
});
}, 1000); // 10 seconds delay
});
return; // End the execution of the function here
}
// Add user's prompt to conversation history with a label
geminiHistory += 'User Prompt: ' + prompt + '\n';
// Handle text-only input
if (!history && (!imageParts || imageParts.length === 0)) {
if (model !== 'gemini-pro') {
return res.status(400).json({ error: 'Invalid model for text-only input. Use gemini-pro.' });
}
// Initialize the Google model for text-only input
const googleModel = genAI.getGenerativeModel({ model: 'gemini-pro', generationConfig: defaultConfig, safetySettings });
// Generate content based on the geminiHistory
const result = await googleModel.generateContent(geminiHistory);
const text = result.response.text();
console.log('Response: ', text)
// Add assistant's response to conversation history
geminiHistory += 'Response: ' + text + '\n';
console.log('Gemini History: ', geminiHistory)
// Send the response
res.json({ success: true, text: text });
}
// Handle text-and-image input (multimodal)
else if (imageParts && imageParts.length > 0 && !history) {
if (model !== 'gemini-pro-vision' && model !== 'gemini-1.5-pro') {
return res.status(400).json({ error: 'Invalid model for text-and-image input. Use gemini-pro-vision.' });
}
// Initialize the Google model for text-and-image input
const googleModel = genAI.getGenerativeModel({ model: model, generationConfig: defaultConfig, safetySettings });
console.log(googleModel);
// Convert image parts to the required format using the new function
// Construct file paths from received filenames and convert image parts
const convertedImageParts = imageParts.map(part => {
// Construct the file path from the filename
const filePath = `public/uploads/${part.filename}`; // Update with the actual path to uploaded images
return convertImageForGemini(filePath, part.mimeType);
});
// Generate content based on the prompt and images
const result = await googleModel.generateContent([prompt, ...convertedImageParts]);
const response = result.response;
const text = response.text();
console.log(text);
// Send the response
res.json({ success: true, text: text });
}
// Handle multi-turn chat functionality
else if (history && history.length > 0) {
if (model !== 'gemini-pro') {
return res.status(400).json({ error: 'Invalid model for chat. Use gemini-pro.' });
}
// Initialize the Google model for chat
const googleModel = genAI.getGenerativeModel({ model: 'gemini-pro', generationConfig: defaultConfig, safetySettings });
// Start the chat with the provided history
const chat = googleModel.startChat({ history });
console.log(chat);
console.log(history);
// Send the user's message and get the response
const result = await chat.sendMessage({ role: "user", parts: prompt });
const response = result.response;
const text = response.text();
console.log("Chat", text);
// Send the response
res.json({ success: true, text: text });
}
} catch (error) {
console.error('Error with Gemini API:', error.message);
res.status(500).json({ error: "Error with Gemini API", details: error.message });
}
});
// Optional streaming implementation
// let text = '';
// for await (const chunk of response.stream) {
// text += chunk.text();
// }
// Streaming can only be properly implemented via
// certain APIs that would defeat the whole purpose.
// See closed issue on this repo for more details.
// Handle POST request to '/message'
let headers;
let apiUrl = '';
let data;
let claudeHistory = [];
app.post('/message', async (req, res) => {
console.log("req.file:", req.file); // Check if the file is received
console.log("Received model ID:", req.body.modelID); // Add this line
const user_message = req.body.message;
const modelID = req.body.modelID || 'gpt-4'; // Extracting model ID from the request
const image_url = req.body.image; // This will now be an URL
console.log("Received request with size: ", JSON.stringify(req.body).length);
isAssistants = false;
// Check for shutdown command
if (user_message === "Bye!") {
console.log("Shutdown message received. Exporting chat and closing server...");
// Export chat history to HTML
const htmlContent = exportChatToHTML();
// Set headers for file download
res.set('Content-Type', 'text/html');
res.set('Content-Disposition', 'attachment; filename="chat_history.html"');
// Send the HTML content
res.send(htmlContent);
// Wait for the response to be fully sent before shutting down
res.end(() => {
console.log("Chat history sent to client, initiating shutdown...");
if (isShuttingDown) {
return res.status(503).send('Server is shutting down');
}
isShuttingDown = true; // Set the shutdown flag
// Delay before shutting down the server to allow file download
setTimeout(() => {
server.close(() => {
console.log("Server successfully shut down.");
});
}, 1000); // 1 seconds delay
});
return; // End the execution of the function here
}
// Retrieve model from the request
let user_input = {
role: "user",
content: [] // Default initialization
};
// Assuming modelID is declared globally and available here
// Determine the structure of user_input.content based on modelID
if (modelID.startsWith('gpt') || modelID.startsWith('claude')) {
// Add text content if present
if (user_message) {
user_input.content.push({ type: "text", text: user_message });
}
if (fileContents) {
console.log(fileContents);
user_input.content.push({ type: "text", text: file_id });
user_input.content.push({ type: "text", text: fileContents });
fileContents = null;
}
// Check for image in the payload
if (req.body.image) {
let base64Image;
// If req.file is defined, it means the image is uploaded as a file
if (req.file) {
base64Image = imageToBase64(req.file.path);
} else {
// If req.file is not present, fetch the image from the URL
base64Image = await imageURLToBase64(req.body.image);
}
if (base64Image) {
user_input.content.push({ type: "text", text: imageName });
if (modelID.startsWith('claude')) {
// Split the base64 string to get the media type and actual base64 data
const [mediaPart, base64Data] = base64Image.split(';base64,');
const mediaType = mediaPart.split(':')[1]; // to get 'image/jpeg' from 'data:image/jpeg'
user_input.content.push({
type: "image",