-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSocket_Send6.html
1246 lines (978 loc) · 41.9 KB
/
Socket_Send6.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Example</title>
</head>
<body>
<input type="text" id="messageInput" placeholder="Enter your message">
<button onclick="sendMessage()">Send Message</button>
<button onclick="sendMessagePhind()">Send Message to Phind</button>
<button onclick="createNewConversation()">Create New Conversation</button>
<button onclick="useOldConversation()">Use Old Conversation</button>
<button onclick="SetUserSystemMessage()">Set The User system message</button>
<button onclick="Speak()">Speak</button>
<!-- Add the checkbox for enabling/disabling -->
<label for="enableCheckbox">Enable User System Message:</label>
<input type="checkbox" id="enableCheckbox">
<script>
let localhost_ws = new WebSocket('ws://localhost:8767');
localhost_ws.addEventListener('message', handleCommand);
localhost_ws.addEventListener('open', onWebSocketOpen);
localhost_ws.addEventListener('close', onWebSocketClose);
console.log("Starting...");
let reconnectInterval;
function onWebSocketOpen(event) {
console.log('WebSocket connection opened');
// You can add any logic that needs to run when the WebSocket connection is opened.
// Clear the reconnect interval if the connection is successful
clearInterval(reconnectInterval);
}
function onWebSocketClose(event) {
console.log('WebSocket connection closed9');
startReconnectInterval()
// You can add any logic that needs to run when the WebSocket connection is closed.
}
// You can add any logic that needs to run when the WebSocket connection is closed.
// Function to start the reconnect interval
function startReconnectInterval() {
// Attempt to reconnect every 5 seconds (adjust interval as needed)
reconnectInterval = setInterval(connectWebSocket, 5000);
}
// Function to connect to the WebSocket server
function connectWebSocket() {
console.log("Attempting to reconnect");
fetch('http://localhost:8000/wake_up', { method: 'GET' })
.then(response => {
if (response.ok) {
// If the GET request is successful, reconnect to WebSocket server
try {
localhost_ws = new WebSocket('ws://localhost:8767');
// Event listener for WebSocket open
localhost_ws.addEventListener('open', function(event) {
console.log('WebSocket connection established');
clearInterval(reconnectInterval);
// Add event listeners for 'message' and 'close' events
localhost_ws.addEventListener('message', handleCommand);
localhost_ws.addEventListener('close', onWebSocketClose);
});
// Event listener for WebSocket error
localhost_ws.addEventListener('error', function(event) {
console.error('WebSoc99ket error:', event);
connectWebSocket()
return;
// Add any error handling logic here
});
} catch (error) {
console.error('W9ebSocket connection error:', error);
// Handle the error as needed
return;
}
} else {
// Handle error response
console.error('Failed to wake up server:', response.status);
}
})
.catch(error => {
console.error('Error waking up server:', error);
});
}
function handleCommand(event) {
console.log("Received COMMAND!!!!!!!!!");
try {
const commandData = JSON.parse(event.data);
if (commandData.type === 'send_message') {
stopAudio()
console.log("send_message command received")
const messageContent = commandData.content;
// Trigger the sendMessage function programmatically with messageContent
console.log("Parent_ID",commandData.parent_id)
sendMessage(messageContent,commandData.parent_id);
}
else if (commandData.type === 'send_message_phind') {
stopAudio()
console.log("send_message_Phind command received")
const messageContent = commandData.content;
sendMessagePhind(messageContent,commandData.parent_id);
}else if (commandData.type === 'create_new_conversation') {
stopAudio()
// Trigger the createNewConversation function programmatically
console.log("create_new_conversation command received")
createNewConversation();
}
else if (commandData.type === "use_old_conversation")
{
stopAudio()
console.log("Attempting to use old conversation")
useOldConversation(commandData.conversation_id)
}
else if (commandData.type === 'user_system_message') {
stopAudio()
console.log("user_system_message command received")
SetUserSystemMessage(commandData.content,commandData.bool);
}
else if (commandData.type === 'Speak') {
stopAudio()
console.log("Speak command received")
Speak();
}
else if (commandData.type ==='PlayBeast')
{
console.log("Play Beast command received")
playAudioBeast(commandData.content)
}
else if (commandData.type ==='PauseBeast')
{
console.log("Pause Beast command received")
pauseAudioBeast()
}
else if (commandData.type === 'ResetBeast')
{
console.log("Reset Beast Command Received")
resetAudioBeast()
}
else if(commandData.type == "Stop_Audio")
{
stopAudio()
console.log("Stop Audio command received")
}
// Add more command handling if needed
} catch (error) {
console.error('Error handling command:', error);
}
}
// Define the URL for the fetch request
const url = 'https://audio.api.speechify.com/generateAudioFiles';
let audioBeast; // Declare audioBeast as a global variable
// Function to play audio with "beast" appended to the function name
function playAudioBeast(data) {
// Define the body of the request
const body = {
audioFormat: "ogg",
paragraphChunks: [data],
voiceParams: {
name: "mrbeast",
engine: "speechify",
languageCode: "en-US"
}
};
// Make the fetch request
fetch(url, {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
// Include any other headers you need, such as authentication tokens
},
body: JSON.stringify(body), // body data type must match "Content-Type" header
})
.then(response => response.json()) // Parse the response as JSON
.then(data => {
// Assuming the response contains a base64 encoded audio stream in a property named 'audioStream'
const audioData = data.audioStream;
// Create a new Audio object
audioBeast = new Audio();
// Set the source of the Audio object to the base64 encoded audio data
audioBeast.src = `data:audio/ogg;base64,${audioData}`;
// Play the audio
audioBeast.play();
})
.catch((error) => {
console.error('Error:', error);
});
}
// Function to pause audio with "beast" appended to the function name
function pauseAudioBeast() {
if (audioBeast) {
audioBeast.pause();
} else {
console.error('No audio element found');
}
}
// Function to reset audio with "beast" appended to the function name
function resetAudioBeast() {
if (audioBeast) {
audioBeast.pause();
audioBeast.currentTime = 0;
} else {
console.error('No audio element found');
}
}
</script>
<script>
const apiUrl = 'https://chat.openai.com/backend-api/conversation';
const socketProtocol = 'json.reliable.webpubsub.azure.v1';
let socket;
let prev_message;
let intervalId;
let wssUrl;
const websocketRequestId = crypto.randomUUID().replace(/-/g, '');
// Base object for the fetch request without body
const fetchBase = {
"method": "POST",
"credentials": "include",
"headers": {
"Content-Type": "application/json",
"OAI-Language": "en-US",
"accept": "text/event-stream"
},
};
class GlobalVariableManager {
constructor() {
this.globalVariables = {}; // Object to store global variables
this.versions = {}; // Object to store versions of global variables
this.activeVariables = {}; // Object to store active variables and their counters
}
// Method to set a variable active
setActive(variable) {
if (!this.activeVariables[variable]) {
this.activeVariables[variable] = 1; // Initialize counter if variable is not active
} else {
this.activeVariables[variable]++; // Increment counter if variable is already active
}
}
// Method to set a variable inactive
setInactive(variable) {
if (this.activeVariables[variable]) {
this.activeVariables[variable]--; // Decrement counter if variable is active
if (this.activeVariables[variable] === 0) {
delete this.activeVariables[variable]; // Remove variable if counter reaches 0
}
}
}
// Method to check if a variable is active
isActive(variable) {
return !!this.activeVariables[variable]; // Return true if variable is active, false otherwise
}
// Method to get the count of active instances of a variable
getActiveCount(variable) {
return this.activeVariables[variable] || 0; // Return the count, or 0 if variable is not active
}
// Method to set a global variable
setGlobalVariable(key, value) {
this.globalVariables[key] = value;
this.updateVersion(key, value);
}
// Method to retrieve a global variable
getGlobalVariable(key) {
return this.globalVariables[key];
}
// Method to modify a global variable
modifyGlobalVariable(key, newValue) {
const oldValue = this.globalVariables[key];
this.setGlobalVariable(key, newValue);
return oldValue;
}
// Method to restore a global variable to a previous version
restoreGlobalVariable(key, version) {
const oldValue = this.versions[key][version];
this.setGlobalVariable(key, oldValue);
return oldValue;
}
// Method to update version of a global variable
updateVersion(key, value) {
if (!this.versions[key]) {
this.versions[key] = [];
}
this.versions[key].push(value);
}
}
// Example usage
const globalManager = new GlobalVariableManager();
let arg2 = {
...fetchBase,
body: JSON.stringify({
action: 'next',
messages: [{
id: `aaa${crypto.randomUUID().slice(3)}`,
author: { role: 'user' },
content: { content_type: 'text', parts: [''] },
metadata: {},
}],
conversation_id: '4d0fecd8-da4a-4d5b-8c03-30f7816d7251',
parent_message_id: 'aaaaaaaa-7317-4af8-b973-477c3a9e6523',
model: 'text-davinci-002-render-sha',
timezone_offset_min: 300,
suggestions: [],
history_and_training_disabled: false,
conversation_mode: { kind: 'primary_assistant', plugin_ids: null },
force_paragen: true,
force_rate_limit: false,
websocket_request_id: websocketRequestId,
}),
};
globalManager.setGlobalVariable('arg2', arg2);
class WebSocketHandler {
constructor() {
this._isUpdate = false;
this._sequenceId = 0;
}
tryGetSequenceId() {
return this._isUpdate ? (this._isUpdate = false,[true, this._sequenceId]) : [false, null];
}
tryUpdate(e) {
// Set this._isUpdate to true
this._isUpdate = true;
// Check if e is greater than this._sequenceId
if (e > this._sequenceId) {
// Update this._sequenceId to e
this._sequenceId = e;
// Return true indicating that the update was successful
return true;
}
// If e is not greater than this._sequenceId, return false
return false;
}
handleMessage(event) {
try {
const receivedData = JSON.parse(event.data);
const { data, sequenceId } = receivedData;
this.tryUpdate(sequenceId);
if (data && data.body) {
const decodedBody = atob(data.body);
if (decodedBody.includes("[DONE]")) {
this.handleDoneMessage();
return;
}
}
this.handleOtherMessages(event.data);
} catch (error) {
console.error("Error:", error.message);
}
}
handleDoneMessage() {
temp_arg2= arg2
const parsedJson = JSON.parse(temp_arg2.body);
const prevMessageData = JSON.parse(prev_message).data;
const { message_id } = prevMessageData;
// Update properties in arg2.body
parsedJson.parent_message_id = message_id;
temp_arg2.body = JSON.stringify(parsedJson);
arg2=temp_arg2
// Send the updated message through the WebSocket
localhost_ws.send(atob(prevMessageData.body));
console.log("Message sent:", atob(prevMessageData.body));
}
handleOtherMessages(data) {
try {
if (JSON.parse(data).event=='disconnected')
{
initializeWebSocket(new WebSocketHandler())
return;
}
if(JSON.parse(data).event=='connected')
{
return;
}
const decodedData = atob(JSON.parse(data).data.body).substring(5);
const parsedData = JSON.parse(decodedData);
//console.log("I said it was the last time",parsedData.type,prev_message)
if (prev_message && parsedData.type == 'title_generation') {
console.log("GHOSTTTTTTTTTTTT TOWNNNNNNNNNNNNn")
temp_arg2= arg2
const parsedJson = JSON.parse(temp_arg2.body);
parsedJson.conversation_id = parsedData.conversation_id;
temp_arg2.body = JSON.stringify(parsedJson);
arg2=temp_arg2
console.log("OneDance DRa_______KE")
} else {
// Handle other WebSocket message logic here
prev_message = data;
}
} catch (error) {
console.error("Error parsing JSON:", error.message);
}
}
reset() {
this._sequenceId = 0;
this._isUpdate = false;
}
}
class CreationWebSocketHandler extends WebSocketHandler {
// Additional logic specific to conversation creation
// ...
}
const voices = ['ember', 'cove', 'juniper', 'sky', 'breeze', '__internal_only_shimmer', '__internal_only_santa'];
// Define a variable to store the currently playing audio element
let currentlyPlayingAudio;
let PAUSEAUDIO=null
function stopAudio()
{
if(PAUSEAUDIO)
{
PAUSEAUDIO();
}
}
async function Speak() {
// Extract conversation_id and message_id from prev_message
const decodedData = JSON.parse(prev_message).data;
console.log(decodedData)
const parsedData = decodedData
const { conversation_id, message_id } = parsedData;
console.log("Parization",prev_message,parsedData)
// Define the input parameters
const input = {
m_message_id: message_id,
conversation_id: conversation_id,
voice: voices[2],
format: 'aac'
};
// Define the API endpoint
speechApiUrl = `https://chat.openai.com/backend-api/synthesize?message_id=${input.m_message_id}&conversa\
tion_id=${input.conversation_id}&voice=${input.voice}&format=${input.format}`;
async function playStream(streamUrl, arg) {
try {
const response = await fetch(streamUrl, arg);
const mediaSource = new MediaSource();
const audioElement = new Audio(); // Create an Audio element
audioElement.style.display = 'none'; // Hide the Audio element
mediaSource.addEventListener('sourceopen', async () => {
try {
const sourceBuffer = mediaSource.addSourceBuffer('audio/aac');
let updating = false;
const reader = response.body.getReader();
async function handleData() {
if (updating) {
await new Promise(resolve => {
sourceBuffer.addEventListener('updateend', () => {
updating = false;
resolve();
}, { once: true });
});
}
const { done, value } = await reader.read();
if (!done) {
updating = true;
sourceBuffer.appendBuffer(value);
handleData(); // Continue handling data recursively
} else {
mediaSource.endOfStream();
}
}
handleData(); // Start handling stream data immediately
} catch (error) {
console.error('Error handling stream data:', error);
}
});
mediaSource.addEventListener('error', (error) => {
console.error('MediaSource error:', error);
});
audioElement.src = URL.createObjectURL(mediaSource); // Set the audio source
// Function to play the audio
function playAudio() {
audioElement.play();
}
// Function to pause the audio
function pauseAudio() {
audioElement.pause();
}
// Function to reset the playback position
function resetAudio() {
audioElement.currentTime = 0;
}
return { playAudio, pauseAudio, resetAudio }; // Return functions to control audio playback
} catch (error) {
console.error('Error fetching stream:', error);
}
}
copy_fetchBase = JSON.parse(JSON.stringify(fetchBase)); //Make a copy not a reference
copy_fetchBase.method = 'GET';
console.log(copy_fetchBase);
const { playAudio, pauseAudio, resetAudio } =
await playStream(speechApiUrl,
copy_fetchBase);
PAUSEAUDIO=pauseAudio
playAudio();
}
// Function to send POST request to set relay data
function setRelayData_Phind(l_apiUrl,l_fetchBase) {
console.log("Problem Post fetch")
// Generate a unique key ID
var uniqueKey = generateKey();
// Format the data into a JSON object
data = {
unique_key:uniqueKey,
apiUrl:l_apiUrl,
arg2: l_fetchBase
};
return fetch('http://localhost:8000/set_relay_data_phind', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.then(() => {
console.log("Successfully set relay data");
// Start fetching relayed data with retry and return the result
return fetchRelayedDataWithRetry_Phind(uniqueKey).then(result => {
return result; // Return the result to the next `then` in the chain
});
})
.catch(error => {
console.error('Error setting relay data:', error);
throw error; // Re-throw the error to propagate it to the next `catch` block
});
}
// Function to fetch relayed data with retry
function fetchRelayedDataWithRetry_Phind(key) {
return new Promise((resolve, reject) => {
const fetchData_Phind = () => {
fetch(`http://localhost:8000/get_relay_data2_phind?key=${key}`)
.then(response => {
if (response.ok) {
return response.json(); // Parse JSON response
} else {
throw new Error('Failed to get relay data');
}
})
.then(responseData => {
// Handle the response data here
console.log('Response data:', responseData);
resolve(responseData); // Resolve the promise with the response data
})
.catch(error => {
// Handle any errors that occurred during the process
console.error('Fetch error:', error);
// Retry the fetch after 1 second if the error indicates another request is being processed
if (error.message === 'Failed to get relay data') {
setTimeout(fetchData_Phind, 1000); // Retry after 1 second
} else {
reject(error); // Reject the promise if it's not a retryable error
}
});
};
// Start the initial fetch
fetchData_Phind();
});
}
// Function to generate a unique key ID
function generateKey() {
return Math.random().toString(36).substring(2) + Date.now().toString(36);
}
// Function to send POST request to set relay data
function setRelayData(l_apiUrl,l_fetchBase) {
console.log("Problem Post fetch")
// Generate a unique key ID
var uniqueKey = generateKey();
// Format the data into a JSON object including the unique key
var data = {
unique_key: uniqueKey, // Keyed as unique_key
apiUrl: l_apiUrl,
arg2: l_fetchBase
};
return fetch('http://localhost:8000/set_relay_data', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.then(() => {
console.log("Successfully set relay data");
// Start fetching relayed data with retry and return the result
return fetchRelayedDataWithRetry(uniqueKey).then(result => {
return result; // Return the result to the next `then` in the chain
});
})
.catch(error => {
console.error('Error setting relay data:', error);
throw error; // Re-throw the error to propagate it to the next `catch` block
});
}
// Function to fetch relayed data with retry by key
function fetchRelayedDataWithRetry(key) {
return new Promise((resolve, reject) => {
const fetchData = () => {
fetch(`http://localhost:8000/get_relay_data2?key=${key}`)
.then(response => {
if (response.ok) {
return response.json(); // Parse JSON response
} else {
throw new Error('Failed to get relay data');
}
})
.then(responseData => {
// Handle the response data here
console.log('Response data:', responseData);
resolve(responseData); // Resolve the promise with the response data
})
.catch(error => {
// Handle any errors that occurred during the process
console.error('Fetch error:', error);
// Retry the fetch after 1 second if the error indicates another request is being processed
if (error.message === 'Failed to get relay data') {
setTimeout(fetchData, 1000); // Retry after 1 second
} else {
reject(error); // Reject the promise if it's not a retryable error
}
});
};
// Start the initial fetch
fetchData();
});
}
function SetUserSystemMessage(message = null, isEnabled = null) {
// Get the message content, either from the parameter or the input field
const messageContent = message !== null ? message : document.getElementById('messageInput').value;
console.log("Setting the user system message (not necessarily on)");
// Get the state of the checkbox or use the provided isEnabled parameter
const checkbox = document.getElementById('enableCheckbox');
const isCheckboxChecked = checkbox.checked;
// Determine the value of isEnabled
const finalIsEnabled = isEnabled !== null ? isEnabled : isCheckboxChecked;
// Create the object for the about_model_message
const userSystemMessageObject = {
about_model_message: messageContent,
about_user_message: '',
disabled_tools: [],
enabled: finalIsEnabled,
};
console.log("Problematic prefetch")
// Send the POST request and handle the response
setRelayData('https://chat.openai.com/backend-api/user_system_messages', {
...fetchBase,
body: JSON.stringify(userSystemMessageObject),
})
.then(response => response)
.then(responseData => {
console.log('Response of Set User message:', responseData);
localhost_ws.send(JSON.stringify(responseData))
// Handle the response as needed
})
.catch(error => {
console.error('Error setting user system message:', error);
});
}
function useOldConversation(conversation_id=null) {
console.log("Using Old Conversation");
// Get the message content, either from the parameter or the input field
conversation_id = conversation_id !== null ? conversation_id : document.getElementById('messageInput').value;
copy_fetchBase = JSON.parse(JSON.stringify(fetchBase)); //Make a copy not a reference
copy_fetchBase.method = 'GET';
setRelayData(`https://chat.openai.com/backend-api/conversation/${conversation_id}`, copy_fetchBase)
.then(response => JSON.parse(response.responseText))
.then(responseData => {
console.log("Old Conversation", responseData);
// Assuming 'responseData' is an object containing the response data
if (responseData?.detail && responseData.detail.startsWith("Can't load conversation")) {
console.log("Starting where I want")
createNewConversation();
return;
}
temp_arg2 = arg2;
const preparsedJson = JSON.parse(temp_arg2.body);
preparsedJson.websocket_request_id = crypto.randomUUID().replace(/-/g, '');
// Assuming you want to set the ID of the first message in the messages array
preparsedJson.conversation_id = responseData.conversation_id;
// Assuming responseData.mapping is an array and you want to get the last element's id
mappingKeys = Object.keys(responseData.mapping);
// Get the last key (UUID)
lastKey = mappingKeys[mappingKeys.length - 1];
// Access the id property of the object corresponding to the last key
preparsedJson.parent_message_id = responseData.mapping[lastKey].id;
temp_arg2.body = JSON.stringify(preparsedJson);
arg2 = temp_arg2;
// Keys to include in the cull
let keysToInclude = [
"conversation_id",
"create_time",
"current_node",
"default_model_slug",
"is_archived",
"title"
];
let cullJsonObject = {};
keysToInclude.forEach(key => {
if (responseData.hasOwnProperty(key)) {
cullJsonObject[key] = responseData[key];
}
});
localhost_ws.send(JSON.stringify(cullJsonObject));
});
}
function createNewConversation() {
console.log('Creating new conversation...');
temp_arg2= arg2
const preparsedJson = JSON.parse(temp_arg2.body);
preparsedJson.websocket_request_id = crypto.randomUUID().replace(/-/g, '');
preparsedJson.messages[0].id = `aaa${crypto.randomUUID().slice(3)}`;
delete preparsedJson.conversation_id;
preparsedJson.parent_message_id = `aaa${crypto.randomUUID().slice(3)}`;
temp_arg2.body = JSON.stringify(preparsedJson);
arg2=temp_arg2
localhost_ws.send(JSON.stringify({ response: "success" }));
(async () => {
try {
const responseBearer = await setRelayData('Get-Bearer-Only', fetchBase);
console.log("Emotion", responseBearer);
fetchBase.headers.Authorization = responseBearer.Bearer;
} catch (error) {
console.error('Error setting relay data:', error);
}
})();
}
function sendMessagePhind(message = null,msg_parent_id=null) {
// Get the message content, either from the parameter or the input field
const messageContent = message !== null ? message : document.getElementById('messageInput').value;
// Check if 'arg2' + func_call_id is not defined
console.log("Stay the night",msg_parent_id)
setRelayData_Phind("",messageContent)
.then(response => {
response=response.Response
// Log the response data
console.log('Phind Response1:', response);
// Assuming response is your JSON object and msg_parent_id is the value you want to assign to message_id
response.message_id = msg_parent_id;
// Convert the response object to a JSON string
const jsonString = JSON.stringify(response);
// Send the JSON string via WebSocket
localhost_ws.send("pdata: " + jsonString);
})
.catch(error => {
console.error('Phind error setting relay data:', error);
});
}
function sendMessage(message = null,msg_parent_id=null) {
// Get the message content, either from the parameter or the input field
const messageContent = message !== null ? message : document.getElementById('messageInput').value;
// Check if 'arg2' + func_call_id is not defined
temp_arg2= arg2
console.log("What we got in here",temp_arg2)
// Update message content in the request payload
preparsedJson = JSON.parse(temp_arg2.body);
preparsedJson.messages[0].content.parts = [messageContent];
temp_arg2.body = JSON.stringify(preparsedJson);
console.log('Message To Be Sent:', preparsedJson);
// Prepare JSON for modification
preparsedJson = JSON.parse(temp_arg2.body);
preparsedJson.websocket_request_id = crypto.randomUUID().replace(/-/g, '');
if(msg_parent_id == null)
{
preparsedJson.messages[0].id = `aaa${crypto.randomUUID().slice(3)}`;
console.log("Tommy G",preparsedJson);
}
else
{
console.log(msg_parent_id)
preparsedJson.messages[0].id = `${msg_parent_id}`;
console.log("Memphis",temp_arg2);
}
temp_arg2.body = JSON.stringify(preparsedJson);
arg2=temp_arg2
setRelayData(apiUrl, temp_arg2)
.then(response => response.responseText)
.then(text => {
console.log('Fetch Conversations API Response1:', text);
if (text.includes('{"detail":"There was a problem with your chat request. Please use a different browser or try again later."}')) {
return setRelayData(apiUrl, temp_arg2)
.then(response => response)
.then(useThatText => {
console.log('Fetch Conversations API Response2:', useThatText);
text = useThatText.responseText;
});
} else {
return text;
}
})
.then(text => {
const dataArray = text.split("\n\n").map(response => {
console.log(response);
// Skip empty responses
if (!response.trim()) {
return null;
}
if (response.replace('data:', '').trim().startsWith("[DONE]")) {
return response.replace('data:', '').trim(); // If response is "[DONE]", leave it as it is
} else if (response.replace('event:', '').trim().startsWith("ping")) {
return null; // Don't store responses starting with "ping"
} else {
return JSON.parse(response.replace('data:', '').trim()); // Otherwise, parse JSON
}
}).filter(Boolean); // Filter out null responses
let messageIndex = dataArray.length - 1;
let lastMessage = dataArray[messageIndex];
console.log("Daughter", lastMessage)
// If last message is "[DONE]"
if (lastMessage === "[DONE]") {
// Look at the last three messages
const lastThreeMessages = dataArray.slice(-3);
console.log(lastThreeMessages)
// If the last but one has data.type as "title_generation"
if (lastThreeMessages[1]?.type === "title_generation") {
// Look just before it to retrieve the message
temp_arg2 = arg2