Diff: STRATO-apps/wordpress_03/app/wp-content/plugins/aimogen-pro/scripts/openai-chat-ajax.js
Keine Baseline-Datei – Diff nur gegen leer.
1
-
1
+
"use strict";
2
+
function aiomaticgetOrCreateUserId() {
3
+
let userId = localStorage.getItem('chatbot_user_id');
4
+
if (!userId) {
5
+
userId = aiomaticgenerateUniqueId();
6
+
localStorage.setItem('chatbot_user_id', userId);
7
+
}
8
+
return userId;
9
+
}
10
+
11
+
function aiomaticgenerateUniqueId() {
12
+
return 'xxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
13
+
let r = Math.random() * 16 | 0,
14
+
v = c === 'x' ? r : (r & 0x3 | 0x8);
15
+
return v.toString(16);
16
+
});
17
+
}
18
+
19
+
function aiomaticwait(time)
20
+
{
21
+
return new Promise(resolve => setTimeout(resolve, time));
22
+
}
23
+
24
+
function aiomaticparseDelay(delayStr) {
25
+
if (typeof delayStr === 'number') {
26
+
return delayStr * 1000;
27
+
} else if (typeof delayStr === 'string') {
28
+
if (delayStr.includes('-')) {
29
+
const [minStr, maxStr] = delayStr.split('-');
30
+
const min = parseFloat(minStr.trim());
31
+
const max = parseFloat(maxStr.trim());
32
+
if (!isNaN(min) && !isNaN(max)) {
33
+
const delaySec = Math.random() * (max - min) + min;
34
+
return delaySec * 1000;
35
+
}
36
+
} else {
37
+
const delaySec = parseFloat(delayStr.trim());
38
+
if (!isNaN(delaySec)) {
39
+
return delaySec * 1000;
40
+
}
41
+
}
42
+
}
43
+
return 0;
44
+
}
45
+
let func_call_var = '';
46
+
let function_call_name = '';
47
+
let function_call_id = '';
48
+
let userStates = {};
49
+
50
+
function aiomaticGetUserState(userId) {
51
+
if (!userStates[userId]) {
52
+
userStates[userId] = {
53
+
messageCount: 0,
54
+
variables: {},
55
+
prompt: "",
56
+
conversationEnded: false,
57
+
processedWorkflows: {},
58
+
actionPerformed: false,
59
+
currentWorkflow: null,
60
+
currentActionIndex: 0,
61
+
messageHistory: []
62
+
};
63
+
}
64
+
return userStates[userId];
65
+
}
66
+
67
+
function aiomaticEvaluateTrigger(trigger, message, userState, aiomatic_chat_ajax_object) {
68
+
if (trigger.operator) {
69
+
const { operator, conditions } = trigger;
70
+
switch (operator) {
71
+
case 'AND':
72
+
return conditions.every(condition => aiomaticEvaluateTrigger(condition, message, userState, aiomatic_chat_ajax_object));
73
+
case 'OR':
74
+
return conditions.some(condition => aiomaticEvaluateTrigger(condition, message, userState, aiomatic_chat_ajax_object));
75
+
case 'NOT':
76
+
return !aiomaticEvaluateTrigger(conditions[0], message, userState, aiomatic_chat_ajax_object);
77
+
default:
78
+
return false;
79
+
}
80
+
} else {
81
+
var messageHistory = userState.messageHistory;
82
+
switch (trigger.type) {
83
+
case 'message_contains':
84
+
return message.includes(trigger.value);
85
+
case 'message_not_contains':
86
+
return !message.includes(trigger.value);
87
+
case 'message_matches_regex':
88
+
return new RegExp(trigger.value).test(message);
89
+
case 'message_not_matches_regex':
90
+
return !new RegExp(trigger.value).test(message);
91
+
case 'message_is':
92
+
return message === trigger.value;
93
+
case 'any_message_contains':
94
+
return messageHistory.some(msg => msg.includes(trigger.value));
95
+
case 'previous_message_is':
96
+
if (messageHistory.length >= 2) {
97
+
const previousMessage = messageHistory[messageHistory.length - 2];
98
+
return previousMessage === trigger.value;
99
+
}
100
+
return false;
101
+
case 'nth_message':
102
+
return userState.messageCount == trigger.value;
103
+
case 'nth_or_larger_message':
104
+
return userState.messageCount >= trigger.value;
105
+
case 'nth_or_smaller_message':
106
+
return userState.messageCount <= trigger.value;
107
+
case 'on_post_id':
108
+
return aiomatic_chat_ajax_object.current_post_id == trigger.value;
109
+
case 'on_post_category_id':
110
+
const categoryIds = aiomatic_chat_ajax_object.current_post_categories.map(category => category.id);
111
+
return Array.isArray(categoryIds) && categoryIds.includes(parseInt(trigger.value, 10));
112
+
case 'on_post_type':
113
+
return aiomatic_chat_ajax_object.current_post_type == trigger.value;
114
+
case 'user_logged_in':
115
+
return aiomatic_chat_ajax_object.is_logged_in == 1;
116
+
case 'user_not_logged_in':
117
+
return aiomatic_chat_ajax_object.is_logged_in == 0;
118
+
case 'user_role_is':
119
+
return aiomatic_chat_ajax_object.user_roles.includes(trigger.value);
120
+
case 'user_role_is_not':
121
+
return !aiomatic_chat_ajax_object.user_roles.includes(trigger.value);
122
+
case 'user_name_is':
123
+
return aiomatic_chat_ajax_object.user_name == trigger.value;
124
+
case 'user_name_is_not':
125
+
return aiomatic_chat_ajax_object.user_name != trigger.value;
126
+
case 'message_starts_with':
127
+
return message.startsWith(trigger.value);
128
+
case 'message_ends_with':
129
+
return message.endsWith(trigger.value);
130
+
case 'message_length_is':
131
+
return message.length === parseInt(trigger.value, 10);
132
+
case 'day_of_week':
133
+
const currentDay = new Date().toLocaleString('en-US', { weekday: 'long' }).toLowerCase();
134
+
return currentDay === trigger.value.toLowerCase();
135
+
case 'time_of_day':
136
+
const currentHour = new Date().getHours();
137
+
const [start, end] = trigger.value.split('-').map(Number); // e.g., "9-17" for 9 AM to 5 PM
138
+
return currentHour >= start && currentHour <= end;
139
+
case 'specific_date':
140
+
const currentDate = new Date().toISOString().split('T')[0]; // Format: "YYYY-MM-DD"
141
+
return currentDate === trigger.value;
142
+
default:
143
+
return false;
144
+
}
145
+
}
146
+
}
147
+
function aiomaticParseMarkdown(md) {
148
+
if (!md) return '';
149
+
return md
150
+
.replace(/^### (.*$)/gim, '<h3>$1</h3>')
151
+
.replace(/^## (.*$)/gim, '<h2>$1</h2>')
152
+
.replace(/^# (.*$)/gim, '<h1>$1</h1>')
153
+
.replace(/\*\*(.*?)\*\*/gim, '<strong>$1</strong>')
154
+
.replace(/\*(.*?)\*/gim, '<em>$1</em>')
155
+
.replace(/~~(.*?)~~/gim, '<del>$1</del>')
156
+
.replace(/`(.*?)`/gim, '<code>$1</code>')
157
+
.replace(/\[(.*?)\]\((.*?)\)/gim, '<a href="$2" target="_blank">$1</a>')
158
+
.replace(/\n/g, '<br>');
159
+
}
160
+
async function aiomaticExecuteAction(action, userState, instance, aiomatic_chat_ajax_object, responded, instant_response, persistent) {
161
+
if(action && action.type)
162
+
{
163
+
switch (action.type)
164
+
{
165
+
case 'send_message':
166
+
let delayMs = 0;
167
+
if (action.delay) {
168
+
delayMs = aiomaticparseDelay(action.delay);
169
+
}
170
+
if (delayMs > 0) {
171
+
await aiomaticwait(delayMs);
172
+
}
173
+
let messageToSend = action.message || '';
174
+
if (messageToSend.includes('|||')) {
175
+
const messageOptions = messageToSend.split('|||').map(m => m.trim()).filter(Boolean);
176
+
messageToSend = messageOptions[Math.floor(Math.random() * messageOptions.length)];
177
+
}
178
+
messageToSend = messageToSend.replace(/%%user_name%%/g, aiomatic_chat_ajax_object.user_name);
179
+
messageToSend = messageToSend.replace(/%%is_user_logged_in%%/g, aiomatic_chat_ajax_object.is_logged_in);
180
+
messageToSend = aiomatic_parseMarkdown(messageToSend);
181
+
aiomaticDisplayBotMessage(messageToSend, instance, aiomatic_chat_ajax_object, responded, instant_response, persistent, 1000);
182
+
userState.actionPerformed = true;
183
+
break;
184
+
case 'append_to_prompt':
185
+
action.value = action.value.replace(/%%user_name%%/g, aiomatic_chat_ajax_object.user_name);
186
+
action.value = action.value.replace(/%%is_user_logged_in%%/g, aiomatic_chat_ajax_object.is_logged_in);
187
+
userState.prompt += ' ' + action.value;
188
+
break;
189
+
case 'end_conversation':
190
+
userState.conversationEnded = true;
191
+
userState.actionPerformed = true;
192
+
break;
193
+
case 'jump_to_workflow':
194
+
userState.currentWorkflow = action.workflow_id;
195
+
userState.currentActionIndex = 0;
196
+
userState.workflowJumped = true;
197
+
userState.actionPerformed = true;
198
+
break;
199
+
case 'redirect_user':
200
+
if (action.value) {
201
+
window.location.href = action.value;
202
+
userState.actionPerformed = true;
203
+
}
204
+
break;
205
+
case 'call_webhook':
206
+
if (action.value) {
207
+
try {
208
+
var sendData = JSON.stringify({
209
+
user_name: aiomatic_chat_ajax_object.user_name,
210
+
is_logged_in: aiomatic_chat_ajax_object.is_logged_in,
211
+
instance_id: instance?.id || null,
212
+
prompt: userState.prompt || '',
213
+
});
214
+
const response = await fetch(action.value.trim(), {
215
+
method: 'POST',
216
+
headers: {
217
+
'Content-Type': 'application/json',
218
+
},
219
+
body: sendData
220
+
});
221
+
if (!response.ok) {
222
+
console.error('Webhook call failed:', response.status, await response.text());
223
+
}
224
+
} catch (error) {
225
+
console.error('Webhook call error:', error);
226
+
}
227
+
let delayMs = 0;
228
+
if (action.delay) {
229
+
delayMs = aiomaticparseDelay(action.delay);
230
+
}
231
+
if (delayMs > 0) {
232
+
await aiomaticwait(delayMs);
233
+
}
234
+
action.message = action.message.replace(/%%user_name%%/g, aiomatic_chat_ajax_object.user_name);
235
+
action.message = action.message.replace(/%%is_user_logged_in%%/g, aiomatic_chat_ajax_object.is_logged_in);
236
+
aiomaticDisplayBotMessage(action.message, instance, aiomatic_chat_ajax_object, responded, instant_response, persistent, 1000);
237
+
userState.actionPerformed = true;
238
+
}
239
+
break;
240
+
default:
241
+
break;
242
+
}
243
+
}
244
+
if(!userState.workflowJumped && action && action.response_options)
245
+
{
246
+
aiomaticaddConversationStarters(action.response_options, instance);
247
+
}
248
+
}
249
+
function aiomaticHideConversationStartersClickHandler(instance)
250
+
{
251
+
return function(e) {
252
+
var xstarter = jQuery('#aiomatic-conversation-starters' + instance);
253
+
if (xstarter) {
254
+
xstarter.hide();
255
+
}
256
+
};
257
+
}
258
+
259
+
async function aiomaticProcessUserMessage(userId, message, instance, aiomatic_chat_ajax_object, responded, instant_response, persistent)
260
+
{
261
+
let userState = aiomaticGetUserState(userId);
262
+
userState.messageHistory.push(message);
263
+
if (userState.messageHistory.length > 150) {
264
+
userState.messageHistory.shift();
265
+
}
266
+
userState.messageCount += 1;
267
+
userState.actionPerformed = false;
268
+
userState.workflowJumped = false;
269
+
var workflows_str = aiomatic_chat_ajax_object.workflows;
270
+
try {
271
+
var workflows = JSON.parse(workflows_str);
272
+
if (!Array.isArray(workflows) || workflows.length === 0) {
273
+
return {
274
+
conversationEnded: userState.conversationEnded,
275
+
actionPerformed: userState.actionPerformed
276
+
};
277
+
}
278
+
} catch (errorBlob) {
279
+
if(workflows_str != '' && workflows_str != '[]')
280
+
{
281
+
console.log('Failed to decode workflows string: ' + workflows_str);
282
+
}
283
+
return {
284
+
conversationEnded: userState.conversationEnded,
285
+
actionPerformed: userState.actionPerformed
286
+
};
287
+
}
288
+
let continueProcessing = true;
289
+
while (continueProcessing) {
290
+
continueProcessing = false;
291
+
if (userState.currentWorkflow !== null) {
292
+
let workflow = workflows.find(wf => wf.id === userState.currentWorkflow);
293
+
if (workflow) {
294
+
let actionIndex = userState.currentActionIndex;
295
+
if (actionIndex < workflow.actions.length && workflow.actions[actionIndex]) {
296
+
let action = workflow.actions[actionIndex];
297
+
await aiomaticExecuteAction(action, userState, instance, aiomatic_chat_ajax_object, responded, instant_response, persistent);
298
+
299
+
if (userState.workflowJumped) {
300
+
continueProcessing = true;
301
+
userState.workflowJumped = false;
302
+
continue;
303
+
}
304
+
305
+
userState.currentActionIndex += 1;
306
+
307
+
if (userState.currentActionIndex >= workflow.actions.length) {
308
+
userState.currentWorkflow = null;
309
+
userState.currentActionIndex = 0;
310
+
}
311
+
} else {
312
+
userState.currentWorkflow = null;
313
+
userState.currentActionIndex = 0;
314
+
}
315
+
} else {
316
+
userState.currentWorkflow = null;
317
+
userState.currentActionIndex = 0;
318
+
}
319
+
} else {
320
+
const sortedWorkflows = workflows
321
+
.filter(workflow => workflow.active)
322
+
.sort((a, b) => (b.priority || 0) - (a.priority || 0));
323
+
324
+
for (let workflow of sortedWorkflows) {
325
+
let maxRepeats = workflow.max_repeat_count || Infinity;
326
+
let timesProcessed = userState.processedWorkflows[workflow.id] || 0;
327
+
328
+
if (timesProcessed >= maxRepeats) {
329
+
continue;
330
+
}
331
+
332
+
let triggersMet = aiomaticEvaluateTrigger(workflow.triggers, message, userState, aiomatic_chat_ajax_object);
333
+
334
+
if (triggersMet) {
335
+
userState.processedWorkflows[workflow.id] = timesProcessed + 1;
336
+
userState.currentWorkflow = workflow.id;
337
+
userState.currentActionIndex = 0;
338
+
if (workflow.actions.length > 0 && workflow.actions[userState.currentActionIndex]) {
339
+
let action = workflow.actions[userState.currentActionIndex];
340
+
await aiomaticExecuteAction(action, userState, instance, aiomatic_chat_ajax_object, responded, instant_response, persistent);
341
+
342
+
if (userState.workflowJumped) {
343
+
continueProcessing = true;
344
+
userState.workflowJumped = false;
345
+
continue;
346
+
}
347
+
348
+
userState.currentActionIndex += 1;
349
+
350
+
if (userState.currentActionIndex >= workflow.actions.length) {
351
+
userState.currentWorkflow = null;
352
+
userState.currentActionIndex = 0;
353
+
}
354
+
} else {
355
+
userState.currentWorkflow = null;
356
+
userState.currentActionIndex = 0;
357
+
}
358
+
359
+
break;
360
+
}
361
+
}
362
+
}
363
+
}
364
+
return {
365
+
conversationEnded: userState.conversationEnded,
366
+
actionPerformed: userState.actionPerformed
367
+
};
368
+
}
369
+
function aiomaticSetDefaultChatbot(bot, instance)
370
+
{
371
+
const hiddenField = document.getElementById('aiomatic_default_hidden_' + instance);
372
+
const button = document.getElementById('aiomatic_default_' + instance + '_' + bot);
373
+
if (hiddenField.value === bot)
374
+
{
375
+
button.classList.remove('active');
376
+
hiddenField.value = '';
377
+
}
378
+
else
379
+
{
380
+
const allButtons = document.querySelectorAll('[id^="aiomatic_default_' + instance + '_"]');
381
+
allButtons.forEach(btn => btn.classList.remove('active'));
382
+
button.classList.add('active');
383
+
hiddenField.value = bot;
384
+
}
385
+
}
386
+
387
+
function aiomaticDisplayBotMessage(hardresponse, instance, aiomatic_chat_ajax_object, responded, instant_response, persistent, waitdelay = 1000)
388
+
{
389
+
var chatbut = jQuery('#aichatsubmitbut' + instance);
390
+
if(instant_response == 'true' || instant_response == 'on')
391
+
{
392
+
aiomaticwait(waitdelay).then(() =>
393
+
{
394
+
var appendx = '<div class="ai-wrapper">';
395
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
396
+
{
397
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
398
+
}
399
+
appendx += '<div class="ai-bubble ai-other">' + hardresponse + '</div>';
400
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
401
+
{
402
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
403
+
}
404
+
appendx += '</div>';
405
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
406
+
appendx = processKatexMarkdown(appendx);
407
+
}
408
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
409
+
appendx = aiomatic_parseMarkdown(appendx);
410
+
}
411
+
var x_input_text = jQuery('#aiomatic_chat_history' + instance).html();
412
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendx);
413
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
414
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
415
+
renderMathInElement(katexContainer, {
416
+
delimiters: [
417
+
418
+
{ left: '\\(', right: '\\)', display: false },
419
+
{ left: '\\[', right: '\\]', display: true }
420
+
],
421
+
throwOnError: false
422
+
});
423
+
}
424
+
var has_speech = false;
425
+
var response_data = hardresponse;
426
+
if(aiomatic_chat_ajax_object.receive_message_sound != '')
427
+
{
428
+
var snd = new Audio(aiomatic_chat_ajax_object.receive_message_sound);
429
+
snd.play();
430
+
}
431
+
if(!jQuery('.aiomatic-gg-unmute').length)
432
+
{
433
+
if(aiomatic_chat_ajax_object.text_speech == 'elevenlabs')
434
+
{
435
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
436
+
response_data = aiomatic_stripHtmlTags(response_data);
437
+
if(response_data != '')
438
+
{
439
+
has_speech = true;
440
+
let speechData = new FormData();
441
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
442
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
443
+
speechData.append('x_input_text', response_data);
444
+
speechData.append('action', 'aiomatic_get_elevenlabs_voice_chat');
445
+
var speechRequest = new XMLHttpRequest();
446
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
447
+
speechRequest.responseType = "arraybuffer";
448
+
speechRequest.ontimeout = () => {
449
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
450
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
451
+
aiomaticRmLoading(chatbut, instance);
452
+
aiomatic_generator_working = false;
453
+
};
454
+
speechRequest.onerror = function ()
455
+
{
456
+
console.error("Network Error");
457
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
458
+
aiomaticRmLoading(chatbut, instance);
459
+
aiomatic_generator_working = false;
460
+
};
461
+
speechRequest.onabort = function ()
462
+
{
463
+
console.error("The request was aborted.");
464
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
465
+
aiomaticRmLoading(chatbut, instance);
466
+
aiomatic_generator_working = false;
467
+
};
468
+
speechRequest.onload = function () {
469
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
470
+
var fr = new FileReader();
471
+
fr.onload = function () {
472
+
var fileText = this.result;
473
+
try {
474
+
var errorMessage = JSON.parse(fileText);
475
+
console.log('ElevenLabs API failed: ' + errorMessage.msg);
476
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
477
+
aiomaticRmLoading(chatbut, instance);
478
+
aiomatic_generator_working = false;
479
+
} catch (errorBlob) {
480
+
var blobUrl = URL.createObjectURL(blob);
481
+
var audioElement = document.createElement('audio');
482
+
audioElement.src = blobUrl;
483
+
audioElement.controls = true;
484
+
audioElement.style.marginTop = "2px";
485
+
audioElement.style.width = "100%";
486
+
audioElement.id = 'audio-element-' + instance;
487
+
audioElement.addEventListener("error", function(event) {
488
+
console.error("Error loading or playing the audio: ", event);
489
+
});
490
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
491
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
492
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
493
+
{
494
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
495
+
var waveform = WaveSurfer.create({
496
+
container: '#waveform-container' + instance,
497
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
498
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
499
+
backend: 'MediaElement',
500
+
height: 60,
501
+
barWidth: 2,
502
+
responsive: true, mediaControls: false, interact: false
503
+
});
504
+
waveform.setMuted(true);
505
+
waveform.load(blobUrl);
506
+
waveform.on('ready', function () {
507
+
waveform.play();
508
+
});
509
+
audioElement.addEventListener('play', function () {
510
+
waveform.play();
511
+
});
512
+
audioElement.addEventListener('pause', function () {
513
+
waveform.pause();
514
+
});
515
+
}
516
+
else
517
+
{
518
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
519
+
}
520
+
audioElement.play();
521
+
aiomaticRmLoading(chatbut, instance);
522
+
aiomatic_generator_working = false;
523
+
}
524
+
}
525
+
fr.readAsText(blob);
526
+
}
527
+
speechRequest.send(speechData);
528
+
}
529
+
}
530
+
else
531
+
{
532
+
if(aiomatic_chat_ajax_object.text_speech == 'openai')
533
+
{
534
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
535
+
response_data = aiomatic_stripHtmlTags(response_data);
536
+
if(response_data != '')
537
+
{
538
+
has_speech = true;
539
+
let speechData = new FormData();
540
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
541
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
542
+
speechData.append('x_input_text', response_data);
543
+
speechData.append('action', 'aiomatic_get_openai_voice_chat');
544
+
var speechRequest = new XMLHttpRequest();
545
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
546
+
speechRequest.responseType = "arraybuffer";
547
+
speechRequest.ontimeout = () => {
548
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
549
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
550
+
aiomaticRmLoading(chatbut, instance);
551
+
aiomatic_generator_working = false;
552
+
};
553
+
speechRequest.onerror = function ()
554
+
{
555
+
console.error("Network Error");
556
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
557
+
aiomaticRmLoading(chatbut, instance);
558
+
aiomatic_generator_working = false;
559
+
};
560
+
speechRequest.onabort = function ()
561
+
{
562
+
console.error("The request was aborted.");
563
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
564
+
aiomaticRmLoading(chatbut, instance);
565
+
aiomatic_generator_working = false;
566
+
};
567
+
speechRequest.onload = function () {
568
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
569
+
var fr = new FileReader();
570
+
fr.onload = function () {
571
+
var fileText = this.result;
572
+
try {
573
+
var errorMessage = JSON.parse(fileText);
574
+
console.log('OpenAI TTS API failed: ' + errorMessage.msg);
575
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
576
+
aiomaticRmLoading(chatbut, instance);
577
+
aiomatic_generator_working = false;
578
+
} catch (errorBlob) {
579
+
var blobUrl = URL.createObjectURL(blob);
580
+
var audioElement = document.createElement('audio');
581
+
audioElement.src = blobUrl;
582
+
audioElement.controls = true;
583
+
audioElement.style.marginTop = "2px";
584
+
audioElement.style.width = "100%";
585
+
audioElement.id = 'audio-element-' + instance;
586
+
audioElement.addEventListener("error", function(event) {
587
+
console.error("Error loading or playing the audio: ", event);
588
+
});
589
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
590
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
591
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
592
+
{
593
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
594
+
var waveform = WaveSurfer.create({
595
+
container: '#waveform-container' + instance,
596
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
597
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
598
+
backend: 'MediaElement',
599
+
height: 60,
600
+
barWidth: 2,
601
+
responsive: true, mediaControls: false, interact: false
602
+
});
603
+
waveform.setMuted(true);
604
+
waveform.load(blobUrl);
605
+
waveform.on('ready', function () {
606
+
waveform.play();
607
+
});
608
+
audioElement.addEventListener('play', function () {
609
+
waveform.play();
610
+
});
611
+
audioElement.addEventListener('pause', function () {
612
+
waveform.pause();
613
+
});
614
+
}
615
+
else
616
+
{
617
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
618
+
}
619
+
audioElement.play();
620
+
aiomaticRmLoading(chatbut, instance);
621
+
aiomatic_generator_working = false;
622
+
}
623
+
}
624
+
fr.readAsText(blob);
625
+
}
626
+
speechRequest.send(speechData);
627
+
}
628
+
}
629
+
else
630
+
{
631
+
if(aiomatic_chat_ajax_object.text_speech == 'google')
632
+
{
633
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
634
+
response_data = aiomatic_stripHtmlTags(response_data);
635
+
if(response_data != '')
636
+
{
637
+
has_speech = true;
638
+
let speechData = new FormData();
639
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
640
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
641
+
speechData.append('x_input_text', response_data);
642
+
speechData.append('action', 'aiomatic_get_google_voice_chat');
643
+
var speechRequest = new XMLHttpRequest();
644
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
645
+
speechRequest.ontimeout = () => {
646
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
647
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
648
+
aiomaticRmLoading(chatbut, instance);
649
+
aiomatic_generator_working = false;
650
+
};
651
+
speechRequest.onerror = function ()
652
+
{
653
+
console.error("Network Error");
654
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
655
+
aiomaticRmLoading(chatbut, instance);
656
+
aiomatic_generator_working = false;
657
+
};
658
+
speechRequest.onabort = function ()
659
+
{
660
+
console.error("The request was aborted.");
661
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
662
+
aiomaticRmLoading(chatbut, instance);
663
+
aiomatic_generator_working = false;
664
+
};
665
+
speechRequest.onload = function () {
666
+
var result = speechRequest.responseText;
667
+
try {
668
+
var jsonresult = JSON.parse(result);
669
+
if(jsonresult.status === 'success'){
670
+
var byteCharacters = atob(jsonresult.audio);
671
+
const byteNumbers = new Array(byteCharacters.length);
672
+
for (let i = 0; i < byteCharacters.length; i++) {
673
+
byteNumbers[i] = byteCharacters.charCodeAt(i);
674
+
}
675
+
const byteArray = new Uint8Array(byteNumbers);
676
+
const blob = new Blob([byteArray], {type: 'audio/mp3'});
677
+
const blobUrl = URL.createObjectURL(blob);
678
+
var audioElement = document.createElement('audio');
679
+
audioElement.src = blobUrl;
680
+
audioElement.controls = true;
681
+
audioElement.style.marginTop = "2px";
682
+
audioElement.style.width = "100%";
683
+
audioElement.id = 'audio-element-' + instance;
684
+
audioElement.addEventListener("error", function(event) {
685
+
console.error("Error loading or playing the audio: ", event);
686
+
});
687
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
688
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
689
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
690
+
{
691
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
692
+
var waveform = WaveSurfer.create({
693
+
container: '#waveform-container' + instance,
694
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
695
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
696
+
backend: 'MediaElement',
697
+
height: 60,
698
+
barWidth: 2,
699
+
responsive: true, mediaControls: false, interact: false
700
+
});
701
+
waveform.setMuted(true);
702
+
waveform.load(blobUrl);
703
+
waveform.on('ready', function () {
704
+
waveform.play();
705
+
});
706
+
audioElement.addEventListener('play', function () {
707
+
waveform.play();
708
+
});
709
+
audioElement.addEventListener('pause', function () {
710
+
waveform.pause();
711
+
});
712
+
}
713
+
else
714
+
{
715
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
716
+
}
717
+
audioElement.play();
718
+
aiomaticRmLoading(chatbut, instance);
719
+
aiomatic_generator_working = false;
720
+
}
721
+
else{
722
+
var errorMessageDetail = 'Google: ' + jsonresult.msg;
723
+
console.log('Google Text-to-Speech error: ' + errorMessageDetail);
724
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
725
+
aiomaticRmLoading(chatbut, instance);
726
+
aiomatic_generator_working = false;
727
+
}
728
+
}
729
+
catch (errorSpeech){
730
+
console.log('Exception in Google Text-to-Speech API: ' + errorSpeech);
731
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
732
+
aiomaticRmLoading(chatbut, instance);
733
+
aiomatic_generator_working = false;
734
+
}
735
+
}
736
+
speechRequest.send(speechData);
737
+
}
738
+
}
739
+
else
740
+
{
741
+
if(aiomatic_chat_ajax_object.text_speech == 'did')
742
+
{
743
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
744
+
response_data = aiomatic_stripHtmlTags(response_data);
745
+
if(response_data != '')
746
+
{
747
+
has_speech = true;
748
+
let speechData = new FormData();
749
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
750
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
751
+
speechData.append('x_input_text', response_data);
752
+
speechData.append('action', 'aiomatic_get_d_id_video_chat');
753
+
var speechRequest = new XMLHttpRequest();
754
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
755
+
speechRequest.ontimeout = () => {
756
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
757
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
758
+
aiomaticRmLoading(chatbut, instance);
759
+
aiomatic_generator_working = false;
760
+
};
761
+
speechRequest.onerror = function ()
762
+
{
763
+
console.error("Network Error");
764
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
765
+
aiomaticRmLoading(chatbut, instance);
766
+
aiomatic_generator_working = false;
767
+
};
768
+
speechRequest.onabort = function ()
769
+
{
770
+
console.error("The request was aborted.");
771
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
772
+
aiomaticRmLoading(chatbut, instance);
773
+
aiomatic_generator_working = false;
774
+
};
775
+
speechRequest.onload = function () {
776
+
var result = speechRequest.responseText;
777
+
try
778
+
{
779
+
var jsonresult = JSON.parse(result);
780
+
if(jsonresult.status === 'success')
781
+
{
782
+
var videoURL = '<video class="ai_video" autoplay="autoplay" controls="controls"><source src="' + jsonresult.video + '" type="video/mp4"></video>';
783
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-video">' + videoURL + '</div>');
784
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
785
+
aiomaticRmLoading(chatbut, instance);
786
+
aiomatic_generator_working = false;
787
+
}
788
+
else
789
+
{
790
+
var errorMessageDetail = 'D-ID: ' + jsonresult.msg;
791
+
console.log('D-ID Text-to-video error: ' + errorMessageDetail);
792
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
793
+
aiomaticRmLoading(chatbut, instance);
794
+
aiomatic_generator_working = false;
795
+
}
796
+
}
797
+
catch (errorSpeech){
798
+
console.log('Exception in D-ID Text-to-video API: ' + errorSpeech);
799
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
800
+
aiomaticRmLoading(chatbut, instance);
801
+
aiomatic_generator_working = false;
802
+
}
803
+
}
804
+
speechRequest.send(speechData);
805
+
}
806
+
}
807
+
else
808
+
{
809
+
if(aiomatic_chat_ajax_object.text_speech == 'didstream')
810
+
{
811
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
812
+
response_data = aiomatic_stripHtmlTags(response_data);
813
+
if(response_data != '')
814
+
{
815
+
if(avatarImageUrl != '' && did_app_id != '')
816
+
{
817
+
if(streamingEpicFail === false)
818
+
{
819
+
has_speech = true;
820
+
myStreamObject.talkToDidStream(response_data);
821
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
822
+
aiomatic_generator_working = false;
823
+
}
824
+
}
825
+
}
826
+
}
827
+
else
828
+
{
829
+
if(aiomatic_chat_ajax_object.text_speech == 'azure')
830
+
{
831
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
832
+
response_data = aiomatic_stripHtmlTags(response_data);
833
+
if(response_data != '')
834
+
{
835
+
if(azure_speech_id != '')
836
+
{
837
+
if(streamingEpicFail === false)
838
+
{
839
+
has_speech = true;
840
+
var ttsvoice = aiomatic_chat_ajax_object.azure_voice;
841
+
var personalVoiceSpeakerProfileID = aiomatic_chat_ajax_object.azure_voice_profile;
842
+
aiomaticRmLoading(chatbut, instance);
843
+
azureSpeakText(response_data, ttsvoice, personalVoiceSpeakerProfileID);
844
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
845
+
aiomatic_generator_working = false;
846
+
}
847
+
}
848
+
}
849
+
}
850
+
else
851
+
{
852
+
if(aiomatic_chat_ajax_object.text_speech == 'free')
853
+
{
854
+
var T2S;
855
+
if("speechSynthesis" in window || speechSynthesis)
856
+
{
857
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
858
+
response_data = aiomatic_stripHtmlTags(response_data);
859
+
if(response_data != '')
860
+
{
861
+
T2S = window.speechSynthesis || speechSynthesis;
862
+
var utter = new SpeechSynthesisUtterance(response_data);
863
+
var voiceSetting = aiomatic_chat_ajax_object.free_voice.split(";");
864
+
var desiredVoiceName = voiceSetting[0].trim();
865
+
var desiredLang = voiceSetting[1].trim();
866
+
var voices = T2S.getVoices();
867
+
var selectedVoice = voices.find(function(voice) {
868
+
return voice.name === desiredVoiceName && voice.lang === desiredLang;
869
+
});
870
+
if (selectedVoice) {
871
+
utter.voice = selectedVoice;
872
+
utter.lang = selectedVoice.lang;
873
+
}
874
+
else
875
+
{
876
+
utter.lang = desiredLang;
877
+
}
878
+
T2S.speak(utter);
879
+
}
880
+
}
881
+
}
882
+
}
883
+
}
884
+
}
885
+
}
886
+
}
887
+
}
888
+
}
889
+
var error_generated = '';
890
+
aiomaticRmLoading(chatbut, instance);
891
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
892
+
var x_input_text = jQuery('#aiomatic_chat_history' + instance).html();
893
+
if((persistent != 'off' && persistent != '0' && persistent != '') && aiomatic_chat_ajax_object.user_id != '0' && error_generated == '')
894
+
{
895
+
var save_persistent = x_input_text;
896
+
if(persistent == 'vector')
897
+
{
898
+
save_persistent = user_question;
899
+
}
900
+
var saving_index = '';
901
+
var main_index = '';
902
+
if(persistent == 'history')
903
+
{
904
+
saving_index = jQuery('#chat-log-identifier' + instance).val();
905
+
main_index = jQuery('#chat-main-identifier' + instance).val();
906
+
}
907
+
jQuery.ajax({
908
+
type: 'POST',
909
+
url: aiomatic_chat_ajax_object.ajax_url,
910
+
data: {
911
+
action: 'aiomatic_user_meta_save',
912
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
913
+
persistent: persistent,
914
+
thread_id: aiomatic_chat_ajax_object.thread_id,
915
+
x_input_text: save_persistent,
916
+
user_id: aiomatic_chat_ajax_object.user_id,
917
+
saving_index: saving_index,
918
+
main_index: main_index
919
+
},
920
+
success: function(result) {
921
+
if(result.name && result.msg)
922
+
{
923
+
var logsdrop = jQuery('#chat-logs-dropdown' + instance);
924
+
if(logsdrop)
925
+
{
926
+
var newChatLogItem = jQuery('<div class="chat-log-item" id="chat-log-item' + saving_index + '" data-id="' + saving_index + '" onclick="aiomatic_trigger_chat_logs(\'' + saving_index + '\', \'' + instance + '\')">' + result.name + '<span onclick="aiomatic_remove_chat_logs(event, \'' + saving_index + '\', \'' + instance + '\');" class="aiomatic-remove-item">X</span></div>');
927
+
var chatLogNew = logsdrop.find('.chat-log-new');
928
+
if (chatLogNew.length)
929
+
{
930
+
var nextSibling = chatLogNew.next();
931
+
if (nextSibling.length && nextSibling.hasClass('date-group-label'))
932
+
{
933
+
newChatLogItem.insertAfter(nextSibling);
934
+
}
935
+
else
936
+
{
937
+
newChatLogItem.insertAfter(chatLogNew);
938
+
}
939
+
}
940
+
else
941
+
{
942
+
logsdrop.append(newChatLogItem);
943
+
}
944
+
}
945
+
}
946
+
},
947
+
error: function(error) {
948
+
console.log('Error while saving persistent user log: ' + error.responseText);
949
+
},
950
+
});
951
+
}
952
+
});
953
+
}
954
+
else
955
+
{
956
+
var i = 0;
957
+
var x_input_text = jQuery('#aiomatic_chat_history' + instance).html();
958
+
function typeWriterBotWrapper(x_input_text, responded)
959
+
{
960
+
return new Promise((resolve, reject) =>
961
+
{
962
+
typeWriterBot(x_input_text, resolve, responded);
963
+
});
964
+
}
965
+
function typeWriterBot(x_input_text, resolve, responded)
966
+
{
967
+
if (i < hardresponse.length)
968
+
{
969
+
var appendx = '<div class="ai-wrapper">';
970
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
971
+
{
972
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
973
+
}
974
+
appendx += '<div class="ai-bubble ai-other">' + hardresponse.substring(0, i + 1) + '</div>';
975
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
976
+
{
977
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
978
+
}
979
+
appendx += '</div>';
980
+
// Append the response to the input field
981
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
982
+
appendx = processKatexMarkdown(appendx);
983
+
}
984
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
985
+
appendx = aiomatic_parseMarkdown(appendx);
986
+
}
987
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendx);
988
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
989
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
990
+
renderMathInElement(katexContainer, {
991
+
delimiters: [
992
+
993
+
{ left: '\\(', right: '\\)', display: false },
994
+
{ left: '\\[', right: '\\]', display: true }
995
+
],
996
+
throwOnError: false
997
+
});
998
+
}
999
+
i++;
1000
+
setTimeout(function() {
1001
+
typeWriterBot(x_input_text, resolve, responded);
1002
+
}, aiomatic_chat_ajax_object.typewriter_delay);
1003
+
}
1004
+
else
1005
+
{
1006
+
x_input_text = jQuery('#aiomatic_chat_history' + instance).html();
1007
+
var has_speech = false;
1008
+
var response_data = hardresponse;
1009
+
if(aiomatic_chat_ajax_object.receive_message_sound != '')
1010
+
{
1011
+
var snd = new Audio(aiomatic_chat_ajax_object.receive_message_sound);
1012
+
snd.play();
1013
+
}
1014
+
if(!jQuery('.aiomatic-gg-unmute').length)
1015
+
{
1016
+
if(aiomatic_chat_ajax_object.text_speech == 'elevenlabs')
1017
+
{
1018
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
1019
+
response_data = aiomatic_stripHtmlTags(response_data);
1020
+
if(response_data != '')
1021
+
{
1022
+
has_speech = true;
1023
+
let speechData = new FormData();
1024
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
1025
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
1026
+
speechData.append('x_input_text', response_data);
1027
+
speechData.append('action', 'aiomatic_get_elevenlabs_voice_chat');
1028
+
var speechRequest = new XMLHttpRequest();
1029
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
1030
+
speechRequest.responseType = "arraybuffer";
1031
+
speechRequest.ontimeout = () => {
1032
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
1033
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1034
+
aiomaticRmLoading(chatbut, instance);
1035
+
aiomatic_generator_working = false;
1036
+
};
1037
+
speechRequest.onerror = function ()
1038
+
{
1039
+
console.error("Network Error");
1040
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1041
+
aiomaticRmLoading(chatbut, instance);
1042
+
aiomatic_generator_working = false;
1043
+
};
1044
+
speechRequest.onabort = function ()
1045
+
{
1046
+
console.error("The request was aborted.");
1047
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1048
+
aiomaticRmLoading(chatbut, instance);
1049
+
aiomatic_generator_working = false;
1050
+
};
1051
+
speechRequest.onload = function () {
1052
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
1053
+
var fr = new FileReader();
1054
+
fr.onload = function () {
1055
+
var fileText = this.result;
1056
+
try {
1057
+
var errorMessage = JSON.parse(fileText);
1058
+
console.log('ElevenLabs API failed: ' + errorMessage.msg);
1059
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1060
+
aiomaticRmLoading(chatbut, instance);
1061
+
aiomatic_generator_working = false;
1062
+
} catch (errorBlob) {
1063
+
var blobUrl = URL.createObjectURL(blob);
1064
+
var audioElement = document.createElement('audio');
1065
+
audioElement.src = blobUrl;
1066
+
audioElement.controls = true;
1067
+
audioElement.style.marginTop = "2px";
1068
+
audioElement.style.width = "100%";
1069
+
audioElement.id = 'audio-element-' + instance;
1070
+
audioElement.addEventListener("error", function(event) {
1071
+
console.error("Error loading or playing the audio: ", event);
1072
+
});
1073
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
1074
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
1075
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
1076
+
{
1077
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
1078
+
var waveform = WaveSurfer.create({
1079
+
container: '#waveform-container' + instance,
1080
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
1081
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
1082
+
backend: 'MediaElement',
1083
+
height: 60,
1084
+
barWidth: 2,
1085
+
responsive: true, mediaControls: false, interact: false
1086
+
});
1087
+
waveform.setMuted(true);
1088
+
waveform.load(blobUrl);
1089
+
waveform.on('ready', function () {
1090
+
waveform.play();
1091
+
});
1092
+
audioElement.addEventListener('play', function () {
1093
+
waveform.play();
1094
+
});
1095
+
audioElement.addEventListener('pause', function () {
1096
+
waveform.pause();
1097
+
});
1098
+
}
1099
+
else
1100
+
{
1101
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1102
+
}
1103
+
audioElement.play();
1104
+
aiomaticRmLoading(chatbut, instance);
1105
+
aiomatic_generator_working = false;
1106
+
}
1107
+
}
1108
+
fr.readAsText(blob);
1109
+
}
1110
+
speechRequest.send(speechData);
1111
+
}
1112
+
}
1113
+
else
1114
+
{
1115
+
if(aiomatic_chat_ajax_object.text_speech == 'openai')
1116
+
{
1117
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
1118
+
response_data = aiomatic_stripHtmlTags(response_data);
1119
+
if(response_data != '')
1120
+
{
1121
+
has_speech = true;
1122
+
let speechData = new FormData();
1123
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
1124
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
1125
+
speechData.append('x_input_text', response_data);
1126
+
speechData.append('action', 'aiomatic_get_openai_voice_chat');
1127
+
var speechRequest = new XMLHttpRequest();
1128
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
1129
+
speechRequest.responseType = "arraybuffer";
1130
+
speechRequest.ontimeout = () => {
1131
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
1132
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1133
+
aiomaticRmLoading(chatbut, instance);
1134
+
aiomatic_generator_working = false;
1135
+
};
1136
+
speechRequest.onerror = function ()
1137
+
{
1138
+
console.error("Network Error");
1139
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1140
+
aiomaticRmLoading(chatbut, instance);
1141
+
aiomatic_generator_working = false;
1142
+
};
1143
+
speechRequest.onabort = function ()
1144
+
{
1145
+
console.error("The request was aborted.");
1146
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1147
+
aiomaticRmLoading(chatbut, instance);
1148
+
aiomatic_generator_working = false;
1149
+
};
1150
+
speechRequest.onload = function () {
1151
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
1152
+
var fr = new FileReader();
1153
+
fr.onload = function () {
1154
+
var fileText = this.result;
1155
+
try {
1156
+
var errorMessage = JSON.parse(fileText);
1157
+
console.log('OpenAI TTS API failed: ' + errorMessage.msg);
1158
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1159
+
aiomaticRmLoading(chatbut, instance);
1160
+
aiomatic_generator_working = false;
1161
+
} catch (errorBlob) {
1162
+
var blobUrl = URL.createObjectURL(blob);
1163
+
var audioElement = document.createElement('audio');
1164
+
audioElement.src = blobUrl;
1165
+
audioElement.controls = true;
1166
+
audioElement.style.marginTop = "2px";
1167
+
audioElement.style.width = "100%";
1168
+
audioElement.id = 'audio-element-' + instance;
1169
+
audioElement.addEventListener("error", function(event) {
1170
+
console.error("Error loading or playing the audio: ", event);
1171
+
});
1172
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
1173
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
1174
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
1175
+
{
1176
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
1177
+
var waveform = WaveSurfer.create({
1178
+
container: '#waveform-container' + instance,
1179
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
1180
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
1181
+
backend: 'MediaElement',
1182
+
height: 60,
1183
+
barWidth: 2,
1184
+
responsive: true, mediaControls: false, interact: false
1185
+
});
1186
+
waveform.setMuted(true);
1187
+
waveform.load(blobUrl);
1188
+
waveform.on('ready', function () {
1189
+
waveform.play();
1190
+
});
1191
+
audioElement.addEventListener('play', function () {
1192
+
waveform.play();
1193
+
});
1194
+
audioElement.addEventListener('pause', function () {
1195
+
waveform.pause();
1196
+
});
1197
+
}
1198
+
else
1199
+
{
1200
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1201
+
}
1202
+
audioElement.play();
1203
+
aiomaticRmLoading(chatbut, instance);
1204
+
aiomatic_generator_working = false;
1205
+
}
1206
+
}
1207
+
fr.readAsText(blob);
1208
+
}
1209
+
speechRequest.send(speechData);
1210
+
}
1211
+
}
1212
+
else
1213
+
{
1214
+
if(aiomatic_chat_ajax_object.text_speech == 'google')
1215
+
{
1216
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
1217
+
response_data = aiomatic_stripHtmlTags(response_data);
1218
+
if(response_data != '')
1219
+
{
1220
+
has_speech = true;
1221
+
let speechData = new FormData();
1222
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
1223
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
1224
+
speechData.append('x_input_text', response_data);
1225
+
speechData.append('action', 'aiomatic_get_google_voice_chat');
1226
+
var speechRequest = new XMLHttpRequest();
1227
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
1228
+
speechRequest.ontimeout = () => {
1229
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
1230
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1231
+
aiomaticRmLoading(chatbut, instance);
1232
+
aiomatic_generator_working = false;
1233
+
};
1234
+
speechRequest.onerror = function ()
1235
+
{
1236
+
console.error("Network Error");
1237
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1238
+
aiomaticRmLoading(chatbut, instance);
1239
+
aiomatic_generator_working = false;
1240
+
};
1241
+
speechRequest.onabort = function ()
1242
+
{
1243
+
console.error("The request was aborted.");
1244
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1245
+
aiomaticRmLoading(chatbut, instance);
1246
+
aiomatic_generator_working = false;
1247
+
};
1248
+
speechRequest.onload = function () {
1249
+
var result = speechRequest.responseText;
1250
+
try {
1251
+
var jsonresult = JSON.parse(result);
1252
+
if(jsonresult.status === 'success'){
1253
+
var byteCharacters = atob(jsonresult.audio);
1254
+
const byteNumbers = new Array(byteCharacters.length);
1255
+
for (let i = 0; i < byteCharacters.length; i++) {
1256
+
byteNumbers[i] = byteCharacters.charCodeAt(i);
1257
+
}
1258
+
const byteArray = new Uint8Array(byteNumbers);
1259
+
const blob = new Blob([byteArray], {type: 'audio/mp3'});
1260
+
const blobUrl = URL.createObjectURL(blob);
1261
+
var audioElement = document.createElement('audio');
1262
+
audioElement.src = blobUrl;
1263
+
audioElement.controls = true;
1264
+
audioElement.style.marginTop = "2px";
1265
+
audioElement.style.width = "100%";
1266
+
audioElement.id = 'audio-element-' + instance;
1267
+
audioElement.addEventListener("error", function(event) {
1268
+
console.error("Error loading or playing the audio: ", event);
1269
+
});
1270
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
1271
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
1272
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
1273
+
{
1274
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
1275
+
var waveform = WaveSurfer.create({
1276
+
container: '#waveform-container' + instance,
1277
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
1278
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
1279
+
backend: 'MediaElement',
1280
+
height: 60,
1281
+
barWidth: 2,
1282
+
responsive: true, mediaControls: false, interact: false
1283
+
});
1284
+
waveform.setMuted(true);
1285
+
waveform.load(blobUrl);
1286
+
waveform.on('ready', function () {
1287
+
waveform.play();
1288
+
});
1289
+
audioElement.addEventListener('play', function () {
1290
+
waveform.play();
1291
+
});
1292
+
audioElement.addEventListener('pause', function () {
1293
+
waveform.pause();
1294
+
});
1295
+
}
1296
+
else
1297
+
{
1298
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1299
+
}
1300
+
audioElement.play();
1301
+
aiomaticRmLoading(chatbut, instance);
1302
+
aiomatic_generator_working = false;
1303
+
}
1304
+
else{
1305
+
var errorMessageDetail = 'Google: ' + jsonresult.msg;
1306
+
console.log('Google Text-to-Speech error: ' + errorMessageDetail);
1307
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1308
+
aiomaticRmLoading(chatbut, instance);
1309
+
aiomatic_generator_working = false;
1310
+
}
1311
+
}
1312
+
catch (errorSpeech){
1313
+
console.log('Exception in Google Text-to-Speech API: ' + errorSpeech);
1314
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1315
+
aiomaticRmLoading(chatbut, instance);
1316
+
aiomatic_generator_working = false;
1317
+
}
1318
+
}
1319
+
speechRequest.send(speechData);
1320
+
}
1321
+
}
1322
+
else
1323
+
{
1324
+
if(aiomatic_chat_ajax_object.text_speech == 'did')
1325
+
{
1326
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
1327
+
response_data = aiomatic_stripHtmlTags(response_data);
1328
+
if(response_data != '')
1329
+
{
1330
+
has_speech = true;
1331
+
let speechData = new FormData();
1332
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
1333
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
1334
+
speechData.append('x_input_text', response_data);
1335
+
speechData.append('action', 'aiomatic_get_d_id_video_chat');
1336
+
var speechRequest = new XMLHttpRequest();
1337
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
1338
+
speechRequest.ontimeout = () => {
1339
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
1340
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1341
+
aiomaticRmLoading(chatbut, instance);
1342
+
aiomatic_generator_working = false;
1343
+
};
1344
+
speechRequest.onerror = function ()
1345
+
{
1346
+
console.error("Network Error");
1347
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1348
+
aiomaticRmLoading(chatbut, instance);
1349
+
aiomatic_generator_working = false;
1350
+
};
1351
+
speechRequest.onabort = function ()
1352
+
{
1353
+
console.error("The request was aborted.");
1354
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1355
+
aiomaticRmLoading(chatbut, instance);
1356
+
aiomatic_generator_working = false;
1357
+
};
1358
+
speechRequest.onload = function () {
1359
+
var result = speechRequest.responseText;
1360
+
try
1361
+
{
1362
+
var jsonresult = JSON.parse(result);
1363
+
if(jsonresult.status === 'success')
1364
+
{
1365
+
var videoURL = '<video class="ai_video" autoplay="autoplay" controls="controls"><source src="' + jsonresult.video + '" type="video/mp4"></video>';
1366
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-video">' + videoURL + '</div>');
1367
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1368
+
aiomaticRmLoading(chatbut, instance);
1369
+
aiomatic_generator_working = false;
1370
+
}
1371
+
else
1372
+
{
1373
+
var errorMessageDetail = 'D-ID: ' + jsonresult.msg;
1374
+
console.log('D-ID Text-to-video error: ' + errorMessageDetail);
1375
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1376
+
aiomaticRmLoading(chatbut, instance);
1377
+
aiomatic_generator_working = false;
1378
+
}
1379
+
}
1380
+
catch (errorSpeech){
1381
+
console.log('Exception in D-ID Text-to-video API: ' + errorSpeech);
1382
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1383
+
aiomaticRmLoading(chatbut, instance);
1384
+
aiomatic_generator_working = false;
1385
+
}
1386
+
}
1387
+
speechRequest.send(speechData);
1388
+
}
1389
+
}
1390
+
else
1391
+
{
1392
+
if(aiomatic_chat_ajax_object.text_speech == 'didstream')
1393
+
{
1394
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
1395
+
response_data = aiomatic_stripHtmlTags(response_data);
1396
+
if(response_data != '')
1397
+
{
1398
+
if(avatarImageUrl != '' && did_app_id != '')
1399
+
{
1400
+
if(streamingEpicFail === false)
1401
+
{
1402
+
has_speech = true;
1403
+
myStreamObject.talkToDidStream(response_data);
1404
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1405
+
aiomatic_generator_working = false;
1406
+
}
1407
+
}
1408
+
}
1409
+
}
1410
+
else
1411
+
{
1412
+
if(aiomatic_chat_ajax_object.text_speech == 'azure')
1413
+
{
1414
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
1415
+
response_data = aiomatic_stripHtmlTags(response_data);
1416
+
if(response_data != '')
1417
+
{
1418
+
if(azure_speech_id != '')
1419
+
{
1420
+
if(streamingEpicFail === false)
1421
+
{
1422
+
has_speech = true;
1423
+
var ttsvoice = aiomatic_chat_ajax_object.azure_voice;
1424
+
var personalVoiceSpeakerProfileID = aiomatic_chat_ajax_object.azure_voice_profile;
1425
+
aiomaticRmLoading(chatbut, instance);
1426
+
azureSpeakText(response_data, ttsvoice, personalVoiceSpeakerProfileID);
1427
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1428
+
aiomatic_generator_working = false;
1429
+
}
1430
+
}
1431
+
}
1432
+
}
1433
+
else
1434
+
{
1435
+
if(aiomatic_chat_ajax_object.text_speech == 'free')
1436
+
{
1437
+
var T2S;
1438
+
if("speechSynthesis" in window || speechSynthesis)
1439
+
{
1440
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
1441
+
response_data = aiomatic_stripHtmlTags(response_data);
1442
+
if(response_data != '')
1443
+
{
1444
+
T2S = window.speechSynthesis || speechSynthesis;
1445
+
var utter = new SpeechSynthesisUtterance(response_data);
1446
+
var voiceSetting = aiomatic_chat_ajax_object.free_voice.split(";");
1447
+
var desiredVoiceName = voiceSetting[0].trim();
1448
+
var desiredLang = voiceSetting[1].trim();
1449
+
var voices = T2S.getVoices();
1450
+
var selectedVoice = voices.find(function(voice)
1451
+
{
1452
+
return voice.name === desiredVoiceName && voice.lang === desiredLang;
1453
+
});
1454
+
if (selectedVoice) {
1455
+
utter.voice = selectedVoice;
1456
+
utter.lang = selectedVoice.lang;
1457
+
}
1458
+
else
1459
+
{
1460
+
utter.lang = desiredLang;
1461
+
}
1462
+
T2S.speak(utter);
1463
+
}
1464
+
}
1465
+
}
1466
+
}
1467
+
}
1468
+
}
1469
+
}
1470
+
}
1471
+
}
1472
+
}
1473
+
// Clear the response container
1474
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
1475
+
// Enable the submit button
1476
+
var chatbut = jQuery('#aichatsubmitbut' + instance);
1477
+
aiomaticRmLoading(chatbut, instance);
1478
+
i = 0;
1479
+
resolve();
1480
+
}
1481
+
}
1482
+
aiomaticwait(1000).then(async () => {
1483
+
var error_generated = '';
1484
+
var x_input_text = jQuery('#aiomatic_chat_history' + instance).html();
1485
+
await typeWriterBotWrapper(x_input_text, responded);
1486
+
var x_input_text = jQuery('#aiomatic_chat_history' + instance).html();
1487
+
if((persistent != 'off' && persistent != '0' && persistent != '') && aiomatic_chat_ajax_object.user_id != '0' && error_generated == '')
1488
+
{
1489
+
var save_persistent = x_input_text;
1490
+
if(persistent == 'vector')
1491
+
{
1492
+
save_persistent = user_question;
1493
+
}
1494
+
var saving_index = '';
1495
+
var main_index = '';
1496
+
if(persistent == 'history')
1497
+
{
1498
+
saving_index = jQuery('#chat-log-identifier' + instance).val();
1499
+
main_index = jQuery('#chat-main-identifier' + instance).val();
1500
+
}
1501
+
jQuery.ajax({
1502
+
type: 'POST',
1503
+
url: aiomatic_chat_ajax_object.ajax_url,
1504
+
data: {
1505
+
action: 'aiomatic_user_meta_save',
1506
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
1507
+
persistent: persistent,
1508
+
thread_id: aiomatic_chat_ajax_object.thread_id,
1509
+
x_input_text: save_persistent,
1510
+
user_id: aiomatic_chat_ajax_object.user_id,
1511
+
saving_index: saving_index,
1512
+
main_index: main_index
1513
+
},
1514
+
success: function(result) {
1515
+
if(result.name && result.msg)
1516
+
{
1517
+
var logsdrop = jQuery('#chat-logs-dropdown' + instance);
1518
+
if(logsdrop)
1519
+
{
1520
+
var newChatLogItem = jQuery('<div class="chat-log-item" id="chat-log-item' + saving_index + '" data-id="' + saving_index + '" onclick="aiomatic_trigger_chat_logs(\'' + saving_index + '\', \'' + instance + '\')">' + result.name + '<span onclick="aiomatic_remove_chat_logs(event, \'' + saving_index + '\', \'' + instance + '\');" class="aiomatic-remove-item">X</span></div>');
1521
+
var chatLogNew = logsdrop.find('.chat-log-new');
1522
+
if (chatLogNew.length)
1523
+
{
1524
+
var nextSibling = chatLogNew.next();
1525
+
if (nextSibling.length && nextSibling.hasClass('date-group-label'))
1526
+
{
1527
+
newChatLogItem.insertAfter(nextSibling);
1528
+
}
1529
+
else
1530
+
{
1531
+
newChatLogItem.insertAfter(chatLogNew);
1532
+
}
1533
+
}
1534
+
else
1535
+
{
1536
+
logsdrop.append(newChatLogItem);
1537
+
}
1538
+
}
1539
+
}
1540
+
},
1541
+
error: function(error) {
1542
+
console.log('Error while saving persistent user log: ' + error.responseText);
1543
+
},
1544
+
});
1545
+
}
1546
+
});
1547
+
}
1548
+
}
1549
+
1550
+
1551
+
function aiomaticRmLoading(btn, instance)
1552
+
{
1553
+
const input = jQuery('#aiomatic_chat_input' + instance);
1554
+
if (!input.prop('chatended')) {
1555
+
btn.removeAttr('disabled');
1556
+
}
1557
+
btn.find('.aiomatic-jumping-dots').remove();
1558
+
}
1559
+
function aiomatic_hide_chat_logs(dataid)
1560
+
{
1561
+
const chatLogsDropdown = document.getElementById('chat-logs-dropdown' + dataid);
1562
+
chatLogsDropdown.classList.remove('cr_visible');
1563
+
chatLogsDropdown.classList.add('cr_none');
1564
+
}
1565
+
function aiomatic_toggle_chat_logs(dataid)
1566
+
{
1567
+
const chatLogsDropdown = document.getElementById('chat-logs-dropdown' + dataid);
1568
+
if (chatLogsDropdown.classList.contains('cr_visible'))
1569
+
{
1570
+
chatLogsDropdown.classList.remove('cr_visible');
1571
+
chatLogsDropdown.classList.add('cr_none');
1572
+
}
1573
+
else
1574
+
{
1575
+
chatLogsDropdown.classList.remove('cr_none');
1576
+
chatLogsDropdown.classList.add('cr_visible');
1577
+
}
1578
+
}
1579
+
function aiomatic_uniqid(prefix = "", moreEntropy = false)
1580
+
{
1581
+
const timestamp = Date.now().toString(16);
1582
+
let uniqueId = prefix + timestamp;
1583
+
if (moreEntropy)
1584
+
{
1585
+
uniqueId += Math.random().toString(16).substring(2);
1586
+
}
1587
+
return uniqueId;
1588
+
}
1589
+
function aiomatic_remove_chat_logs(event, dataid, instance)
1590
+
{
1591
+
event.stopPropagation();
1592
+
var chatbut = jQuery('#aichatsubmitbut' + instance);
1593
+
aiomaticLoading(chatbut);
1594
+
var aiomatic_chat_ajax_object = window["aiomatic_chat_ajax_object" + instance];
1595
+
let frmData = new FormData();
1596
+
frmData.append('nonce', aiomatic_chat_ajax_object.nonce);
1597
+
frmData.append('dataid', dataid);
1598
+
frmData.append('persistent_guests', aiomatic_chat_ajax_object.persistent_guests);
1599
+
frmData.append('persistent', aiomatic_chat_ajax_object.persistent);
1600
+
frmData.append('action', 'aiomatic_remove_chat_logs');
1601
+
var frmRequest = new XMLHttpRequest();
1602
+
frmRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
1603
+
frmRequest.ontimeout = () =>
1604
+
{
1605
+
aiomaticRmLoading(chatbut, instance);
1606
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
1607
+
return;
1608
+
};
1609
+
frmRequest.onerror = function ()
1610
+
{
1611
+
aiomaticRmLoading(chatbut, instance);
1612
+
console.error("Network Error");
1613
+
return;
1614
+
};
1615
+
frmRequest.onabort = function ()
1616
+
{
1617
+
aiomaticRmLoading(chatbut, instance);
1618
+
console.error("The request was aborted.");
1619
+
return;
1620
+
};
1621
+
frmRequest.onload = function ()
1622
+
{
1623
+
var result = frmRequest.responseText;
1624
+
try
1625
+
{
1626
+
var jsonresult = JSON.parse(result);
1627
+
if(jsonresult.status === 'success')
1628
+
{
1629
+
var logi = jQuery('#chat-log-item' + dataid);
1630
+
if(logi)
1631
+
{
1632
+
logi.remove();
1633
+
}
1634
+
aiomaticRmLoading(chatbut, instance);
1635
+
return;
1636
+
}
1637
+
else
1638
+
{
1639
+
console.log('Chat log loading error: ' + jsonresult.msg);
1640
+
aiomaticRmLoading(chatbut, instance);
1641
+
return;
1642
+
}
1643
+
}
1644
+
catch (errorSpeech)
1645
+
{
1646
+
console.log('Exception in chat log loading: ' + errorSpeech);
1647
+
aiomaticRmLoading(chatbut, instance);
1648
+
return;
1649
+
}
1650
+
}
1651
+
frmRequest.send(frmData);
1652
+
}
1653
+
function aiomatic_trigger_chat_logs(dataid, instance)
1654
+
{
1655
+
var chatbut = jQuery('#aichatsubmitbut' + instance);
1656
+
aiomaticLoading(chatbut);
1657
+
var aiomatic_chat_ajax_object = window["aiomatic_chat_ajax_object" + instance];
1658
+
let frmData = new FormData();
1659
+
var initMessage = '';
1660
+
if(dataid == 'new-chat')
1661
+
{
1662
+
initMessage = aiomatic_chat_ajax_object.chat_initial_messages;
1663
+
}
1664
+
aiomatic_hide_chat_logs(instance);
1665
+
frmData.append('nonce', aiomatic_chat_ajax_object.nonce);
1666
+
frmData.append('dataid', dataid);
1667
+
frmData.append('init_message', initMessage);
1668
+
frmData.append('persistent_guests', aiomatic_chat_ajax_object.persistent_guests);
1669
+
frmData.append('persistent', aiomatic_chat_ajax_object.persistent);
1670
+
frmData.append('action', 'aiomatic_load_chat_conversation_data');
1671
+
var frmRequest = new XMLHttpRequest();
1672
+
frmRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
1673
+
frmRequest.ontimeout = () =>
1674
+
{
1675
+
aiomaticRmLoading(chatbut, instance);
1676
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
1677
+
return;
1678
+
};
1679
+
frmRequest.onerror = function ()
1680
+
{
1681
+
aiomaticRmLoading(chatbut, instance);
1682
+
console.error("Network Error");
1683
+
return;
1684
+
};
1685
+
frmRequest.onabort = function ()
1686
+
{
1687
+
aiomaticRmLoading(chatbut, instance);
1688
+
console.error("The request was aborted.");
1689
+
return;
1690
+
};
1691
+
frmRequest.onload = function ()
1692
+
{
1693
+
var result = frmRequest.responseText;
1694
+
try
1695
+
{
1696
+
var jsonresult = JSON.parse(result);
1697
+
if(jsonresult.status === 'success')
1698
+
{
1699
+
if(jsonresult.data.data)
1700
+
{
1701
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
1702
+
jsonresult.data.data = processKatexMarkdown(jsonresult.data.data);
1703
+
}
1704
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
1705
+
jsonresult.data.data = aiomatic_parseMarkdown(jsonresult.data.data);
1706
+
}
1707
+
jQuery('#aiomatic_chat_history' + instance).html(jsonresult.data.data);
1708
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
1709
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
1710
+
renderMathInElement(katexContainer, {
1711
+
delimiters: [
1712
+
1713
+
{ left: '\\(', right: '\\)', display: false },
1714
+
{ left: '\\[', right: '\\]', display: true }
1715
+
],
1716
+
throwOnError: false
1717
+
});
1718
+
}
1719
+
aiomaticRmLoading(chatbut, instance);
1720
+
if(dataid == 'new-chat')
1721
+
{
1722
+
jQuery('#chat-log-identifier' + instance).val(aiomatic_uniqid());
1723
+
}
1724
+
else
1725
+
{
1726
+
jQuery('#chat-log-identifier' + instance).val(dataid);
1727
+
}
1728
+
return;
1729
+
}
1730
+
else
1731
+
{
1732
+
jQuery('#aiomatic_chat_history' + instance).html(jsonresult.data.data);
1733
+
aiomaticRmLoading(chatbut, instance);
1734
+
if(dataid == 'new-chat')
1735
+
{
1736
+
jQuery('#chat-log-identifier' + instance).val(aiomatic_uniqid());
1737
+
}
1738
+
else
1739
+
{
1740
+
jQuery('#chat-log-identifier' + instance).val(dataid);
1741
+
}
1742
+
return;
1743
+
}
1744
+
}
1745
+
else
1746
+
{
1747
+
console.log('Chat log loading error: ' + jsonresult.msg);
1748
+
aiomaticRmLoading(chatbut, instance);
1749
+
return;
1750
+
}
1751
+
}
1752
+
catch (errorSpeech)
1753
+
{
1754
+
console.log('Exception in chat log loading: ' + errorSpeech);
1755
+
aiomaticRmLoading(chatbut, instance);
1756
+
return;
1757
+
}
1758
+
}
1759
+
frmRequest.send(frmData);
1760
+
}
1761
+
function aiomatic_stripHtmlTags(str)
1762
+
{
1763
+
var tempDiv = document.createElement("div");
1764
+
tempDiv.innerHTML = str;
1765
+
return tempDiv.textContent || tempDiv.innerText || "";
1766
+
}
1767
+
function aiomatic_parse_html_to_gptobj(html)
1768
+
{
1769
+
if(html == '')
1770
+
{
1771
+
return [];
1772
+
}
1773
+
const parser = new DOMParser();
1774
+
const doc = parser.parseFromString(html, 'text/html');
1775
+
let messages = [];
1776
+
const allMessages = doc.querySelectorAll('.ai-bubble');
1777
+
allMessages.forEach(message =>
1778
+
{
1779
+
const role = message.classList.contains('ai-other') ? 'assistant' : 'user';
1780
+
messages.push({ role: role, content: message.innerHTML.trim() });
1781
+
});
1782
+
return messages;
1783
+
}
1784
+
function aiomaticSleep(ms)
1785
+
{
1786
+
return new Promise(resolve => setTimeout(resolve, ms));
1787
+
}
1788
+
function aiomaticHtmlEncode(text) {
1789
+
const entityMap = {
1790
+
'&': '&',
1791
+
'<': '<',
1792
+
'>': '>',
1793
+
'"': '"',
1794
+
"'": ''',
1795
+
'/': '/'
1796
+
};
1797
+
1798
+
return String(text).replace(/[&<>"'\/]/g, (match) => entityMap[match])
1799
+
}
1800
+
var avatarSynthesizer;
1801
+
var peerConnection;
1802
+
var previousAnimationFrameTimestamp = 0;
1803
+
1804
+
function azureSpeakText(spokenText, ttsVoice, personalVoiceSpeakerProfileID)
1805
+
{
1806
+
if(document.getElementById('audio'))
1807
+
{
1808
+
document.getElementById('audio').muted = false;
1809
+
}
1810
+
let spokenSsml = `<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xmlns:mstts='http://www.w3.org/2001/mstts' xml:lang='en-US'><voice name='${ttsVoice}'><mstts:ttsembedding speakerProfileId='${personalVoiceSpeakerProfileID}'><mstts:leadingsilence-exact value='0'/>${aiomaticHtmlEncode(spokenText)}</mstts:ttsembedding></voice></speak>`
1811
+
console.log("[" + (new Date()).toISOString() + "] Speak request sent.")
1812
+
try
1813
+
{
1814
+
if(avatarSynthesizer)
1815
+
{
1816
+
avatarSynthesizer.speakSsmlAsync(spokenSsml).then(
1817
+
(result) => {
1818
+
if (result.reason === SpeechSDK.ResultReason.SynthesizingAudioCompleted) {
1819
+
console.log("[" + (new Date()).toISOString() + "] Speech synthesized to speaker for text [ " + spokenText + " ]. Result ID: " + result.resultId)
1820
+
} else {
1821
+
console.log("[" + (new Date()).toISOString() + "] Unable to speak text. Result ID: " + result.resultId)
1822
+
if (result.reason === SpeechSDK.ResultReason.Canceled) {
1823
+
let cancellationDetails = SpeechSDK.CancellationDetails.fromResult(result)
1824
+
console.log(cancellationDetails.reason)
1825
+
if (cancellationDetails.reason === SpeechSDK.CancellationReason.Error) {
1826
+
console.log(cancellationDetails.errorDetails)
1827
+
}
1828
+
}
1829
+
}
1830
+
});
1831
+
}
1832
+
}
1833
+
catch(error)
1834
+
{
1835
+
console.log("Error in processing " + error);
1836
+
}
1837
+
}
1838
+
function azureStartAndDisplayStream(instance, azure_speech_id, cogSvcRegion, privateEndpoint, customVoiceEndpointId, talkingAvatarCharacter, talkingAvatarStyle)
1839
+
{
1840
+
const cogSvcSubKey = azure_speech_id;
1841
+
privateEndpoint = privateEndpoint.slice(8);
1842
+
1843
+
let speechSynthesisConfig;
1844
+
if (privateEndpoint) {
1845
+
speechSynthesisConfig = SpeechSDK.SpeechConfig.fromEndpoint(new URL(`wss://${privateEndpoint}/tts/cognitiveservices/websocket/v1?enableTalkingAvatar=true`), cogSvcSubKey);
1846
+
}
1847
+
else
1848
+
{
1849
+
speechSynthesisConfig = SpeechSDK.SpeechConfig.fromSubscription(cogSvcSubKey, cogSvcRegion);
1850
+
}
1851
+
speechSynthesisConfig.endpointId = customVoiceEndpointId;
1852
+
const videoFormat = new SpeechSDK.AvatarVideoFormat();
1853
+
let videoCropTopLeftX = 600;
1854
+
let videoCropBottomRightX = 1320;
1855
+
videoFormat.setCropRange(new SpeechSDK.Coordinate(videoCropTopLeftX, 0), new SpeechSDK.Coordinate(videoCropBottomRightX, 1080));
1856
+
const avatarConfig = new SpeechSDK.AvatarConfig(talkingAvatarCharacter, talkingAvatarStyle, videoFormat);
1857
+
avatarConfig.backgroundColor = '#00FF00FF';
1858
+
avatarConfig.customized = false;
1859
+
avatarSynthesizer = new SpeechSDK.AvatarSynthesizer(speechSynthesisConfig, avatarConfig);
1860
+
avatarSynthesizer.avatarEventReceived = function (s, e) {
1861
+
var offsetMessage = ", offset from session start: " + e.offset / 10000 + "ms.";
1862
+
if (e.offset === 0) {
1863
+
offsetMessage = "";
1864
+
}
1865
+
console.log("[" + (new Date()).toISOString() + "] Event received: " + e.description + offsetMessage);
1866
+
}
1867
+
const xhr = new XMLHttpRequest();
1868
+
if (privateEndpoint) {
1869
+
xhr.open("GET", `https://${privateEndpoint}/tts/cognitiveservices/avatar/relay/token/v1`);
1870
+
} else {
1871
+
xhr.open("GET", `https://${cogSvcRegion}.tts.speech.microsoft.com/cognitiveservices/avatar/relay/token/v1`);
1872
+
}
1873
+
xhr.setRequestHeader("Ocp-Apim-Subscription-Key", cogSvcSubKey);
1874
+
xhr.addEventListener("readystatechange", function() {
1875
+
if (this.readyState === 4) {
1876
+
try
1877
+
{
1878
+
const responseData = JSON.parse(this.responseText);
1879
+
const iceServerUrl = responseData.Urls[0];
1880
+
const iceServerUsername = responseData.Username;
1881
+
const iceServerCredential = responseData.Password;
1882
+
setupWebRTCAzure(iceServerUrl, iceServerUsername, iceServerCredential, instance);
1883
+
}
1884
+
catch (errorSpeech){
1885
+
console.log('Exception Azure stream: ' + errorSpeech);
1886
+
}
1887
+
}
1888
+
})
1889
+
xhr.send();
1890
+
}
1891
+
var globalinstance = '';
1892
+
function makeBackgroundTransparent(timestamp) {
1893
+
// Throttle the frame rate to 30 FPS to reduce CPU usage
1894
+
if (timestamp - previousAnimationFrameTimestamp > 30) {
1895
+
var video = document.getElementById('video')
1896
+
var tmpCanvas = document.getElementById('tmpCanvas' + globalinstance)
1897
+
var tmpCanvasContext = tmpCanvas.getContext('2d', { willReadFrequently: true })
1898
+
tmpCanvasContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight)
1899
+
if (video.videoWidth > 0) {
1900
+
let frame = tmpCanvasContext.getImageData(0, 0, video.videoWidth, video.videoHeight)
1901
+
for (let i = 0; i < frame.data.length / 4; i++) {
1902
+
let r = frame.data[i * 4 + 0]
1903
+
let g = frame.data[i * 4 + 1]
1904
+
let b = frame.data[i * 4 + 2]
1905
+
if (g - 150 > r + b) {
1906
+
// Set alpha to 0 for pixels that are close to green
1907
+
frame.data[i * 4 + 3] = 0
1908
+
} else if (g + g > r + b) {
1909
+
// Reduce green part of the green pixels to avoid green edge issue
1910
+
var adjustment = (g - (r + b) / 2) / 3
1911
+
r += adjustment
1912
+
g -= adjustment * 2
1913
+
b += adjustment
1914
+
frame.data[i * 4 + 0] = r
1915
+
frame.data[i * 4 + 1] = g
1916
+
frame.data[i * 4 + 2] = b
1917
+
// Reduce alpha part for green pixels to make the edge smoother
1918
+
var a = Math.max(0, 255 - adjustment * 4)
1919
+
frame.data[i * 4 + 3] = a
1920
+
}
1921
+
}
1922
+
1923
+
var canvas = document.getElementById('canvas' + globalinstance)
1924
+
var canvasContext = canvas.getContext('2d')
1925
+
canvasContext.putImageData(frame, 0, 0);
1926
+
}
1927
+
1928
+
previousAnimationFrameTimestamp = timestamp;
1929
+
}
1930
+
1931
+
window.requestAnimationFrame(makeBackgroundTransparent);
1932
+
}
1933
+
function setupWebRTCAzure(iceServerUrl, iceServerUsername, iceServerCredential, instance) {
1934
+
peerConnection = new RTCPeerConnection({
1935
+
iceServers: [{
1936
+
urls: [ iceServerUrl ],
1937
+
username: iceServerUsername,
1938
+
credential: iceServerCredential
1939
+
}]
1940
+
});
1941
+
peerConnection.ontrack = function (event) {
1942
+
var remoteVideoDiv = document.getElementById('remoteVideo' + instance)
1943
+
for (var i = 0; i < remoteVideoDiv.childNodes.length; i++) {
1944
+
if (remoteVideoDiv.childNodes[i].localName === event.track.kind) {
1945
+
remoteVideoDiv.removeChild(remoteVideoDiv.childNodes[i])
1946
+
}
1947
+
}
1948
+
1949
+
const mediaPlayer = document.createElement(event.track.kind)
1950
+
mediaPlayer.id = event.track.kind
1951
+
mediaPlayer.srcObject = event.streams[0]
1952
+
mediaPlayer.autoplay = true
1953
+
document.getElementById('remoteVideo' + instance).appendChild(mediaPlayer)
1954
+
document.getElementById('overlayArea' + instance).hidden = false
1955
+
if (event.track.kind === 'video') {
1956
+
mediaPlayer.playsInline = true
1957
+
remoteVideoDiv = document.getElementById('remoteVideo' + instance)
1958
+
var canvas = document.getElementById('canvas' + instance)
1959
+
if (true) {
1960
+
remoteVideoDiv.style.width = '0.1px'
1961
+
canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height)
1962
+
canvas.hidden = false
1963
+
}
1964
+
else {
1965
+
canvas.hidden = true
1966
+
}
1967
+
1968
+
mediaPlayer.addEventListener('play', () => {
1969
+
if (true) {
1970
+
globalinstance = instance;
1971
+
window.requestAnimationFrame(makeBackgroundTransparent)
1972
+
} else {
1973
+
remoteVideoDiv.style.width = mediaPlayer.videoWidth / 2 + 'px'
1974
+
}
1975
+
})
1976
+
}
1977
+
else
1978
+
{
1979
+
mediaPlayer.muted = true
1980
+
}
1981
+
}
1982
+
1983
+
// Listen to data channel, to get the event from the server
1984
+
peerConnection.addEventListener("datachannel", event => {
1985
+
const dataChannel = event.channel
1986
+
dataChannel.onmessage = e => {
1987
+
console.log("[" + (new Date()).toISOString() + "] WebRTC event received: " + e.data);
1988
+
try
1989
+
{
1990
+
var jsd = JSON.parse(e.data);
1991
+
if(jsd.event.eventType == 'EVENT_TYPE_SWITCH_TO_IDLE')
1992
+
{
1993
+
var chatbut = jQuery('#aichatsubmitbut' + globalinstance);
1994
+
aiomaticRmLoading(chatbut, instance);
1995
+
console.log('idle ' + globalinstance);
1996
+
}
1997
+
}
1998
+
catch (errorSpeech){
1999
+
console.log('Exception datachannel: ' + errorSpeech);
2000
+
}
2001
+
}
2002
+
})
2003
+
2004
+
// This is a workaround to make sure the data channel listening is working by creating a data channel from the client side
2005
+
var c = peerConnection.createDataChannel("eventChannel")
2006
+
2007
+
// Make necessary update to the web page when the connection state changes
2008
+
peerConnection.oniceconnectionstatechange = e => {
2009
+
console.log("WebRTC status: " + peerConnection.iceConnectionState)
2010
+
}
2011
+
2012
+
// Offer to receive 1 audio, and 1 video track
2013
+
peerConnection.addTransceiver('video', { direction: 'sendrecv' })
2014
+
peerConnection.addTransceiver('audio', { direction: 'sendrecv' })
2015
+
2016
+
// start avatar, establish WebRTC connection
2017
+
avatarSynthesizer.startAvatarAsync(peerConnection).then((r) => {
2018
+
if (r.reason === SpeechSDK.ResultReason.SynthesizingAudioCompleted) {
2019
+
console.log("[" + (new Date()).toISOString() + "] Avatar started. Result ID: " + r.resultId)
2020
+
} else {
2021
+
console.log("[" + (new Date()).toISOString() + "] Unable to start avatar. Result ID: " + r.resultId)
2022
+
if (r.reason === SpeechSDK.ResultReason.Canceled) {
2023
+
let cancellationDetails = SpeechSDK.CancellationDetails.fromResult(r)
2024
+
if (cancellationDetails.reason === SpeechSDK.CancellationReason.Error) {
2025
+
console.log(cancellationDetails.errorDetails)
2026
+
};
2027
+
console.log("Unable to start avatar: " + cancellationDetails.errorDetails);
2028
+
}
2029
+
}
2030
+
}).catch(
2031
+
(error) => {
2032
+
console.log("[" + (new Date()).toISOString() + "] Avatar failed to start. Error: " + error)
2033
+
}
2034
+
);
2035
+
}
2036
+
const myStreamObject = {
2037
+
async startAndDisplayStream(avatarImageUrl, chatId, apiKey)
2038
+
{
2039
+
let streamingdebugging = false;
2040
+
function myCleverDecodeHtml(html) {
2041
+
var txt = document.createElement("textarea");
2042
+
txt.innerHTML = html;
2043
+
return txt.value;
2044
+
}
2045
+
let idleVideoUrl = null;
2046
+
var aiomatic_chat_ajax_object = window["aiomatic_chat_ajax_object" + chatId];
2047
+
const RTCPeerConnection = (
2048
+
window.RTCPeerConnection ||
2049
+
window.webkitRTCPeerConnection ||
2050
+
window.mozRTCPeerConnection
2051
+
).bind(window);
2052
+
2053
+
let peerConnection;
2054
+
let streamId;
2055
+
let sessionId;
2056
+
let sessionClientAnswer;
2057
+
2058
+
let statsIntervalId;
2059
+
let videoIsPlaying;
2060
+
let lastBytesReceived;
2061
+
const talkVideo = document.getElementById('talk-video' + chatId);
2062
+
if(talkVideo === undefined || talkVideo === null)
2063
+
{
2064
+
return;
2065
+
}
2066
+
const loadingIndicator = document.getElementById('aiomatic-loading-indicator' + chatId);
2067
+
talkVideo.setAttribute('playsinline', '');
2068
+
function whenFinishedPlaying(videoElement) {
2069
+
return new Promise((resolve) => {
2070
+
videoElement.onended = () => {
2071
+
resolve();
2072
+
};
2073
+
});
2074
+
}
2075
+
if (peerConnection && peerConnection.connectionState === 'connected') {
2076
+
return;
2077
+
}
2078
+
2079
+
stopAllStreams();
2080
+
closePC();
2081
+
2082
+
const sessionResponse = await fetchWithRetries(`https://api.d-id.com/talks/streams`, {
2083
+
method: 'POST',
2084
+
headers: {
2085
+
Authorization: `Basic ` + apiKey,
2086
+
'Content-Type': 'application/json',
2087
+
},
2088
+
body: JSON.stringify({
2089
+
source_url: avatarImageUrl,
2090
+
}),
2091
+
});
2092
+
2093
+
const { id: newStreamId, offer, ice_servers: iceServers, session_id: newSessionId } = await sessionResponse.json();
2094
+
streamId = newStreamId;
2095
+
sessionId = newSessionId;
2096
+
2097
+
try {
2098
+
sessionClientAnswer = await createPeerConnection(offer, iceServers);
2099
+
} catch (e) {
2100
+
console.log('Error during streaming setup', e);
2101
+
stopAllStreams();
2102
+
closePC();
2103
+
throw e;
2104
+
}
2105
+
2106
+
const sdpResponse = await fetch(`https://api.d-id.com/talks/streams/${streamId}/sdp`, {
2107
+
method: 'POST',
2108
+
headers: {
2109
+
Authorization: `Basic ` + apiKey,
2110
+
'Content-Type': 'application/json',
2111
+
},
2112
+
body: JSON.stringify({
2113
+
answer: sessionClientAnswer,
2114
+
session_id: sessionId,
2115
+
}),
2116
+
});
2117
+
if(sdpResponse.ok !== true)
2118
+
{
2119
+
console.log('Error during stream starting', JSON.stringify(sdpResponse));
2120
+
stopAllStreams();
2121
+
closePC();
2122
+
throw Exception('Error: ' + JSON.stringify(sdpResponse));
2123
+
}
2124
+
this.talkToDidStream = async function(myText)
2125
+
{
2126
+
if (peerConnection?.signalingState === 'stable' || peerConnection?.iceConnectionState === 'connected')
2127
+
{
2128
+
myText = myText.replace(/^<p>|<\/p>$/g, '');
2129
+
var myvoice = aiomatic_chat_ajax_object.did_voice;
2130
+
if(aiomatic_chat_ajax_object.overwrite_voice != '')
2131
+
{
2132
+
myvoice = aiomatic_chat_ajax_object.overwrite_voice;
2133
+
}
2134
+
let xscript = {
2135
+
script: {
2136
+
type: 'text',
2137
+
input: myCleverDecodeHtml(myText),
2138
+
},
2139
+
driver_url: 'bank://lively/',
2140
+
config: {
2141
+
stitch: true,
2142
+
},
2143
+
session_id: sessionId,
2144
+
};
2145
+
if(myvoice != '')
2146
+
{
2147
+
let didVoiceExp = myvoice.split(':');
2148
+
if(didVoiceExp[1] !== undefined) {
2149
+
if(didVoiceExp[0].trim() !== '') {
2150
+
xscript.script.provider = {
2151
+
type: didVoiceExp[0].trim().toLowerCase(),
2152
+
voice_id: didVoiceExp[1].trim()
2153
+
};
2154
+
2155
+
if(didVoiceExp[2] !== undefined) {
2156
+
xscript.script.provider.voice_config = {
2157
+
style: didVoiceExp[2].trim()
2158
+
};
2159
+
}
2160
+
}
2161
+
}
2162
+
}
2163
+
const talkResponse = await fetchWithRetries(`https://api.d-id.com/talks/streams/${streamId}`, {
2164
+
method: 'POST',
2165
+
headers: {
2166
+
Authorization: `Basic ` + apiKey,
2167
+
'Content-Type': 'application/json',
2168
+
},
2169
+
body: JSON.stringify(xscript),
2170
+
});
2171
+
}
2172
+
};
2173
+
2174
+
this.destroyConnectionStreaming = async function()
2175
+
{
2176
+
await fetch(`https://api.d-id.com/talks/streams/${streamId}`, {
2177
+
method: 'DELETE',
2178
+
headers: {
2179
+
Authorization: `Basic ` + apiKey,
2180
+
'Content-Type': 'application/json',
2181
+
},
2182
+
body: JSON.stringify({ session_id: sessionId }),
2183
+
});
2184
+
2185
+
stopAllStreams();
2186
+
closePC();
2187
+
};
2188
+
2189
+
function aiomaticStreamRmLoading(btn){
2190
+
btn.removeAttr('disabled');
2191
+
btn.find('.aiomatic-jumping-dots').remove();
2192
+
}
2193
+
function onIceGatheringStateChange() {
2194
+
if(streamingdebugging)
2195
+
{
2196
+
console.log('ICE gathering status: ' + peerConnection.iceGatheringState);
2197
+
}
2198
+
}
2199
+
function onIceCandidate(event) {
2200
+
if(streamingdebugging)
2201
+
{
2202
+
console.log('onIceCandidate', event);
2203
+
}
2204
+
if (event.candidate) {
2205
+
const { candidate, sdpMid, sdpMLineIndex } = event.candidate;
2206
+
2207
+
fetch(`https://api.d-id.com/talks/streams/${streamId}/ice`, {
2208
+
method: 'POST',
2209
+
headers: {
2210
+
Authorization: `Basic ` + apiKey,
2211
+
'Content-Type': 'application/json',
2212
+
},
2213
+
body: JSON.stringify({
2214
+
candidate,
2215
+
sdpMid,
2216
+
sdpMLineIndex,
2217
+
session_id: sessionId,
2218
+
}),
2219
+
});
2220
+
}
2221
+
}
2222
+
function onIceConnectionStateChange() {
2223
+
if(streamingdebugging)
2224
+
{
2225
+
console.log('ICE status: ' + peerConnection.iceConnectionState);
2226
+
}
2227
+
if (peerConnection.iceConnectionState === 'failed' || peerConnection.iceConnectionState === 'closed') {
2228
+
stopAllStreams();
2229
+
closePC();
2230
+
}
2231
+
}
2232
+
function onConnectionStateChange() {
2233
+
if(streamingdebugging)
2234
+
{
2235
+
console.log('Peer connection state: ' + peerConnection.connectionState);
2236
+
}
2237
+
}
2238
+
function onSignalingStateChange() {
2239
+
if(streamingdebugging)
2240
+
{
2241
+
console.log('Signal status change: ' + peerConnection.signalingState);
2242
+
}
2243
+
}
2244
+
2245
+
function onVideoStatusChange(videoIsPlaying, stream)
2246
+
{
2247
+
let status;
2248
+
if (videoIsPlaying)
2249
+
{
2250
+
status = 'streaming';
2251
+
const remoteStream = stream;
2252
+
setVideoElement(remoteStream);
2253
+
} else {
2254
+
status = 'empty';
2255
+
whenFinishedPlaying(talkVideo);
2256
+
playIdleVideo();
2257
+
}
2258
+
if(streamingdebugging)
2259
+
{
2260
+
console.log('Streaming status change: ' + status);
2261
+
}
2262
+
}
2263
+
2264
+
function onTrack(event)
2265
+
{
2266
+
if (!event.track) return;
2267
+
2268
+
statsIntervalId = setInterval(async () => {
2269
+
const stats = await peerConnection.getStats(event.track);
2270
+
stats.forEach((report) => {
2271
+
if (report.type === 'inbound-rtp' && report.mediaType === 'video') {
2272
+
const videoStatusChanged = videoIsPlaying !== report.bytesReceived > lastBytesReceived;
2273
+
2274
+
if (videoStatusChanged) {
2275
+
videoIsPlaying = report.bytesReceived > lastBytesReceived;
2276
+
onVideoStatusChange(videoIsPlaying, event.streams[0]);
2277
+
}
2278
+
lastBytesReceived = report.bytesReceived;
2279
+
}
2280
+
});
2281
+
}, 500);
2282
+
}
2283
+
2284
+
async function createPeerConnection(offer, iceServers) {
2285
+
if (!peerConnection) {
2286
+
peerConnection = new RTCPeerConnection({ iceServers });
2287
+
peerConnection.addEventListener('icegatheringstatechange', onIceGatheringStateChange, true);
2288
+
peerConnection.addEventListener('icecandidate', onIceCandidate, true);
2289
+
peerConnection.addEventListener('iceconnectionstatechange', onIceConnectionStateChange, true);
2290
+
peerConnection.addEventListener('connectionstatechange', onConnectionStateChange, true);
2291
+
peerConnection.addEventListener('signalingstatechange', onSignalingStateChange, true);
2292
+
peerConnection.addEventListener('track', onTrack, true);
2293
+
}
2294
+
2295
+
await peerConnection.setRemoteDescription(offer);
2296
+
if(streamingdebugging)
2297
+
{
2298
+
console.log('set remote sdp OK');
2299
+
}
2300
+
2301
+
const sessionClientAnswer = await peerConnection.createAnswer();
2302
+
if(streamingdebugging)
2303
+
{
2304
+
console.log('create local sdp OK');
2305
+
}
2306
+
2307
+
await peerConnection.setLocalDescription(sessionClientAnswer);
2308
+
if(streamingdebugging)
2309
+
{
2310
+
console.log('set local sdp OK');
2311
+
}
2312
+
2313
+
return sessionClientAnswer;
2314
+
}
2315
+
2316
+
function setVideoElement(stream) {
2317
+
if (!stream) return;
2318
+
talkVideo.muted = false;
2319
+
talkVideo.srcObject = stream;
2320
+
talkVideo.loop = false;
2321
+
if (talkVideo.paused) {
2322
+
talkVideo
2323
+
.play()
2324
+
.then((_) => {})
2325
+
.catch((e) => {});
2326
+
}
2327
+
}
2328
+
async function playIdleVideo()
2329
+
{
2330
+
if (!idleVideoUrl)
2331
+
{
2332
+
talkVideo.poster = aiomatic_chat_ajax_object.did_image;
2333
+
talkVideo.src = "";
2334
+
talkVideo.load();
2335
+
// If not, call the generateIdleVideo function to get it
2336
+
let speechData = new FormData();
2337
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
2338
+
speechData.append('did_image', aiomatic_chat_ajax_object.did_image);
2339
+
speechData.append('action', 'aiomatic_get_d_id_default_video_chat');
2340
+
var speechRequest = new XMLHttpRequest();
2341
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
2342
+
speechRequest.ontimeout = () => {
2343
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
2344
+
return; // Exit the function if unable to retrieve the video
2345
+
};
2346
+
speechRequest.onerror = function ()
2347
+
{
2348
+
console.error("Network Error");
2349
+
return; // Exit the function if unable to retrieve the video
2350
+
};
2351
+
speechRequest.onabort = function ()
2352
+
{
2353
+
console.error("The request was aborted.");
2354
+
return; // Exit the function if unable to retrieve the video
2355
+
};
2356
+
speechRequest.onload = function () {
2357
+
var result = speechRequest.responseText;
2358
+
try
2359
+
{
2360
+
var jsonresult = JSON.parse(result);
2361
+
if(jsonresult.status === 'success')
2362
+
{
2363
+
idleVideoUrl = jsonresult.video;
2364
+
talkVideo.muted = false;
2365
+
talkVideo.src = idleVideoUrl;
2366
+
talkVideo.poster = "";
2367
+
talkVideo.loop = true;
2368
+
talkVideo.play().catch(e => console.error('Error playing idle video:', e));
2369
+
}
2370
+
else
2371
+
{
2372
+
var errorMessageDetail = 'D-ID: ' + jsonresult.msg;
2373
+
console.log('D-ID Text-to-video error: ' + errorMessageDetail);
2374
+
return; // Exit the function if unable to retrieve the video
2375
+
}
2376
+
}
2377
+
catch (errorSpeech){
2378
+
console.log('Exception in D-ID Text-to-video API: ' + errorSpeech);
2379
+
return; // Exit the function if unable to retrieve the video
2380
+
}
2381
+
}
2382
+
speechRequest.send(speechData);
2383
+
}
2384
+
else
2385
+
{
2386
+
talkVideo.srcObject = null;
2387
+
talkVideo.src = idleVideoUrl;
2388
+
talkVideo.loop = true;
2389
+
talkVideo.play().catch(e => console.error('Error playing idle video:', e));
2390
+
}
2391
+
loadingIndicator.style.display = 'none';
2392
+
var chatbut = jQuery('#aichatsubmitbut' + chatId);
2393
+
aiomaticStreamRmLoading(chatbut);
2394
+
}
2395
+
2396
+
function stopAllStreams() {
2397
+
if (talkVideo.srcObject) {
2398
+
if(streamingdebugging)
2399
+
{
2400
+
console.log('stopping video streams');
2401
+
}
2402
+
talkVideo.srcObject.getTracks().forEach((track) => track.stop());
2403
+
talkVideo.srcObject = null;
2404
+
}
2405
+
}
2406
+
2407
+
function closePC(pc = peerConnection) {
2408
+
if (!pc) return;
2409
+
if(streamingdebugging)
2410
+
{
2411
+
console.log('stopping peer connection');
2412
+
}
2413
+
pc.close();
2414
+
pc.removeEventListener('icegatheringstatechange', onIceGatheringStateChange, true);
2415
+
pc.removeEventListener('icecandidate', onIceCandidate, true);
2416
+
pc.removeEventListener('iceconnectionstatechange', onIceConnectionStateChange, true);
2417
+
pc.removeEventListener('connectionstatechange', onConnectionStateChange, true);
2418
+
pc.removeEventListener('signalingstatechange', onSignalingStateChange, true);
2419
+
pc.removeEventListener('track', onTrack, true);
2420
+
clearInterval(statsIntervalId);
2421
+
if(streamingdebugging)
2422
+
{
2423
+
console.log('stopped peer connection');
2424
+
}
2425
+
if (pc === peerConnection) {
2426
+
peerConnection = null;
2427
+
}
2428
+
}
2429
+
const maxRetryCount = 3;
2430
+
const maxDelaySec = 4;
2431
+
2432
+
async function fetchWithRetries(url, options, retries = 1) {
2433
+
if(streamingdebugging)
2434
+
{
2435
+
console.log('Fetching (' + retries + '): ' + url);
2436
+
}
2437
+
try {
2438
+
return await fetch(url, options);
2439
+
} catch (err) {
2440
+
if (retries <= maxRetryCount) {
2441
+
const delay = Math.min(Math.pow(2, retries) / 4 + Math.random(), maxDelaySec) * 1000;
2442
+
2443
+
await new Promise((resolve) => setTimeout(resolve, delay));
2444
+
2445
+
console.log(`Request failed, retrying ${retries}/${maxRetryCount}. Error ${err}`);
2446
+
return fetchWithRetries(url, options, retries + 1);
2447
+
} else {
2448
+
throw new Error(`Max retries exceeded. error: ${err}`);
2449
+
}
2450
+
}
2451
+
}
2452
+
}
2453
+
}
2454
+
function aiomatic_hasConsented(chatID)
2455
+
{
2456
+
return localStorage.getItem('chatbotConsent' + chatID) === 'true';
2457
+
}
2458
+
function aiomatic_toggleOverlay(instance, chatID)
2459
+
{
2460
+
const chatbotContainer = document.getElementById('openai-ai-chat-form-' + instance);
2461
+
const chatbotImageContainer = document.getElementById('openai-ai-image-form-' + instance);
2462
+
const chatbotOverlay = document.getElementById('aiomatic-chatbot-overlay' + instance);
2463
+
if(chatbotContainer && chatbotOverlay)
2464
+
{
2465
+
if (aiomatic_hasConsented(chatID)) {
2466
+
chatbotOverlay.style.display = 'none';
2467
+
chatbotContainer.classList.remove('blur');
2468
+
} else {
2469
+
chatbotOverlay.style.display = 'flex';
2470
+
chatbotContainer.classList.add('blur');
2471
+
}
2472
+
}
2473
+
if(chatbotImageContainer && chatbotOverlay)
2474
+
{
2475
+
if (aiomatic_hasConsented(chatID)) {
2476
+
chatbotOverlay.style.display = 'none';
2477
+
chatbotImageContainer.classList.remove('blur');
2478
+
} else {
2479
+
chatbotOverlay.style.display = 'flex';
2480
+
chatbotImageContainer.classList.add('blur');
2481
+
}
2482
+
}
2483
+
}
2484
+
2485
+
jQuery(document).ready(function($)
2486
+
{
2487
+
$('.aiomatic-chat-holder').each(function( )
2488
+
{
2489
+
var instance = $(this).attr("instance");
2490
+
var chatID = $(this).attr("data-id");
2491
+
initChatbotAiomatic(instance);
2492
+
var bot_displayed = false;
2493
+
if(window["aiomatic_chat_ajax_object" + instance].autoload == '1')
2494
+
{
2495
+
var aiomatic_chat_ajax_object = window["aiomatic_chat_ajax_object" + instance];
2496
+
const chatOnce = window["aiomatic_chat_ajax_object" + instance].page_load_chat_once == '1';
2497
+
const storageKey = "aiomatic_chat_autoloaded";
2498
+
if (!chatOnce || !localStorage.getItem(storageKey))
2499
+
{
2500
+
const allowedUrlsRaw = window["aiomatic_chat_ajax_object" + instance].page_load_chat_urls || '';
2501
+
const allowedUrls = allowedUrlsRaw
2502
+
.split('\n')
2503
+
.map(url => url.trim())
2504
+
.filter(url => url.length > 0);
2505
+
2506
+
const currentUrl = window.location.href;
2507
+
const shouldAutoload =
2508
+
allowedUrls.length === 0 ||
2509
+
allowedUrls.some(url => currentUrl.includes(url));
2510
+
2511
+
if (shouldAutoload) {
2512
+
var responded = '';
2513
+
if(aiomatic_chat_ajax_object.bots_data)
2514
+
{
2515
+
var matchedBots = [];
2516
+
var defaultBot = jQuery('#aiomatic_default_hidden_' + instance);
2517
+
if(defaultBot)
2518
+
{
2519
+
defaultBot = defaultBot.val();
2520
+
if(defaultBot && aiomaticIsNumeric(defaultBot))
2521
+
{
2522
+
aiomatic_chat_ajax_object.bots_data.forEach((relement) => {
2523
+
if(relement.ID == defaultBot)
2524
+
{
2525
+
matchedBotID = relement.ID;
2526
+
matchedBotName = relement.name;
2527
+
matchedBotPrompt = relement.prompt;
2528
+
matchedBotModel = relement.model;
2529
+
matchedBotAssistantID = relement.assistentid;
2530
+
responded = ' aiomatic-ainum-' + matchedBotID;
2531
+
}});
2532
+
}
2533
+
}
2534
+
matchedBots = aiomatic_chat_ajax_object.bots_data.filter(bot => {
2535
+
const nameWithoutSpaces = bot.name.replace(/\s+/g, '');
2536
+
return input_text.includes(`@${bot.name}`) || input_text.includes(`@${nameWithoutSpaces}`);
2537
+
});
2538
+
if (matchedBots.length > 0)
2539
+
{
2540
+
const matchedBot = matchedBots[0];
2541
+
matchedBotID = matchedBot.ID;
2542
+
matchedBotName = matchedBot.name;
2543
+
matchedBotPrompt = matchedBot.prompt;
2544
+
matchedBotModel = matchedBot.model;
2545
+
matchedBotAssistantID = matchedBot.assistentid;
2546
+
responded = ' aiomatic-ainum-' + matchedBotID;
2547
+
}
2548
+
}
2549
+
const delay = parseInt(window["aiomatic_chat_ajax_object" + instance].autoload_delay);
2550
+
if (!isNaN(delay))
2551
+
{
2552
+
setTimeout(function () {
2553
+
bot_displayed = true;
2554
+
$('#aiomatic-open-button' + instance).click();
2555
+
if (chatOnce) {
2556
+
localStorage.setItem(storageKey, '1');
2557
+
}
2558
+
if(window["aiomatic_chat_ajax_object" + instance].page_load_chat_message != '')
2559
+
{
2560
+
aiomaticDisplayBotMessage(window["aiomatic_chat_ajax_object" + instance].page_load_chat_message, instance, window["aiomatic_chat_ajax_object" + instance], responded, aiomatic_chat_ajax_object.instant_response, aiomatic_chat_ajax_object.persistent, 1000);
2561
+
}
2562
+
}, delay);
2563
+
}
2564
+
else
2565
+
{
2566
+
bot_displayed = true;
2567
+
$('#aiomatic-open-button' + instance).click();
2568
+
if (chatOnce) {
2569
+
localStorage.setItem(storageKey, '1');
2570
+
}
2571
+
if(window["aiomatic_chat_ajax_object" + instance].page_load_chat_message != '')
2572
+
{
2573
+
aiomaticDisplayBotMessage(window["aiomatic_chat_ajax_object" + instance].page_load_chat_message, instance, window["aiomatic_chat_ajax_object" + instance], responded, aiomatic_chat_ajax_object.instant_response, aiomatic_chat_ajax_object.persistent, 1000);
2574
+
}
2575
+
}
2576
+
}
2577
+
}
2578
+
}
2579
+
if(bot_displayed == false)
2580
+
{
2581
+
if(window["aiomatic_chat_ajax_object" + instance].page_exit_chat == '1')
2582
+
{
2583
+
var aiomatic_chat_ajax_object = window["aiomatic_chat_ajax_object" + instance];
2584
+
const chatOnce = window["aiomatic_chat_ajax_object" + instance].page_exit_chat_once == '1';
2585
+
const storageKey_exit = "aiomatic_chat_autoloaded_exit";
2586
+
if (!chatOnce || !localStorage.getItem(storageKey_exit))
2587
+
{
2588
+
const allowedUrlsRaw = window["aiomatic_chat_ajax_object" + instance].page_exit_chat_urls || '';
2589
+
const allowedUrls = allowedUrlsRaw
2590
+
.split('\n')
2591
+
.map(url => url.trim())
2592
+
.filter(url => url.length > 0);
2593
+
2594
+
const currentUrl = window.location.href;
2595
+
const shouldAutoload =
2596
+
allowedUrls.length === 0 ||
2597
+
allowedUrls.some(url => currentUrl.includes(url));
2598
+
2599
+
if (shouldAutoload) {
2600
+
var responded = '';
2601
+
if(aiomatic_chat_ajax_object.bots_data)
2602
+
{
2603
+
var matchedBots = [];
2604
+
var defaultBot = jQuery('#aiomatic_default_hidden_' + instance);
2605
+
if(defaultBot)
2606
+
{
2607
+
defaultBot = defaultBot.val();
2608
+
if(defaultBot && aiomaticIsNumeric(defaultBot))
2609
+
{
2610
+
aiomatic_chat_ajax_object.bots_data.forEach((relement) => {
2611
+
if(relement.ID == defaultBot)
2612
+
{
2613
+
matchedBotID = relement.ID;
2614
+
matchedBotName = relement.name;
2615
+
matchedBotPrompt = relement.prompt;
2616
+
matchedBotModel = relement.model;
2617
+
matchedBotAssistantID = relement.assistentid;
2618
+
responded = ' aiomatic-ainum-' + matchedBotID;
2619
+
}});
2620
+
}
2621
+
}
2622
+
matchedBots = aiomatic_chat_ajax_object.bots_data.filter(bot => {
2623
+
const nameWithoutSpaces = bot.name.replace(/\s+/g, '');
2624
+
return input_text.includes(`@${bot.name}`) || input_text.includes(`@${nameWithoutSpaces}`);
2625
+
});
2626
+
if (matchedBots.length > 0)
2627
+
{
2628
+
const matchedBot = matchedBots[0];
2629
+
matchedBotID = matchedBot.ID;
2630
+
matchedBotName = matchedBot.name;
2631
+
matchedBotPrompt = matchedBot.prompt;
2632
+
matchedBotModel = matchedBot.model;
2633
+
matchedBotAssistantID = matchedBot.assistentid;
2634
+
responded = ' aiomatic-ainum-' + matchedBotID;
2635
+
}
2636
+
}
2637
+
var displayed_exit = false;
2638
+
document.addEventListener('mouseout', function (e) {
2639
+
e = e ? e : window.event;
2640
+
2641
+
if (e.target.tagName.toLowerCase() == "input")
2642
+
return;
2643
+
2644
+
var vpWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
2645
+
2646
+
if (e.clientX >= (vpWidth - 50))
2647
+
return;
2648
+
2649
+
if (e.clientY >= 50)
2650
+
return;
2651
+
2652
+
var from = e.relatedTarget || e.toElement;
2653
+
if (!from)
2654
+
{
2655
+
if(displayed_exit === false)
2656
+
{
2657
+
const chatbotContainer = document.getElementById('openai-ai-chat-form-' + instance);
2658
+
const chatstyle = window.getComputedStyle(chatbotContainer);
2659
+
if (chatstyle.display === 'none' || chatstyle.visibility === 'hidden' || chatstyle.opacity === '0') {
2660
+
displayed_exit = true;
2661
+
bot_displayed = true;
2662
+
$('#aiomatic-open-button' + instance).click();
2663
+
if (chatOnce) {
2664
+
localStorage.setItem(storageKey_exit, '1');
2665
+
}
2666
+
if(window["aiomatic_chat_ajax_object" + instance].page_exit_chat_message != '')
2667
+
{
2668
+
aiomaticDisplayBotMessage(window["aiomatic_chat_ajax_object" + instance].page_exit_chat_message, instance, window["aiomatic_chat_ajax_object" + instance], responded, aiomatic_chat_ajax_object.instant_response, aiomatic_chat_ajax_object.persistent, 1000);
2669
+
}
2670
+
}
2671
+
}
2672
+
}
2673
+
});
2674
+
}
2675
+
}
2676
+
}
2677
+
}
2678
+
if(bot_displayed == false)
2679
+
{
2680
+
if(window["aiomatic_chat_ajax_object" + instance].page_scroll_chat == '1')
2681
+
{
2682
+
var aiomatic_chat_ajax_object = window["aiomatic_chat_ajax_object" + instance];
2683
+
const chatOnce = window["aiomatic_chat_ajax_object" + instance].page_scroll_chat_once == '1';
2684
+
const scrollPercent = parseInt(aiomatic_chat_ajax_object.page_scroll_chat_percent) || 50;
2685
+
const storageKey_scroll = "aiomatic_chat_autoloaded_scroll";
2686
+
if (!chatOnce || !localStorage.getItem(storageKey_scroll))
2687
+
{
2688
+
const allowedUrlsRaw = window["aiomatic_chat_ajax_object" + instance].page_scroll_chat_urls || '';
2689
+
const allowedUrls = allowedUrlsRaw
2690
+
.split('\n')
2691
+
.map(url => url.trim())
2692
+
.filter(url => url.length > 0);
2693
+
2694
+
const currentUrl = window.location.href;
2695
+
const shouldAutoload =
2696
+
allowedUrls.length === 0 ||
2697
+
allowedUrls.some(url => currentUrl.includes(url));
2698
+
2699
+
if (shouldAutoload) {
2700
+
var responded = '';
2701
+
if(aiomatic_chat_ajax_object.bots_data)
2702
+
{
2703
+
var matchedBots = [];
2704
+
var defaultBot = jQuery('#aiomatic_default_hidden_' + instance);
2705
+
if(defaultBot)
2706
+
{
2707
+
defaultBot = defaultBot.val();
2708
+
if(defaultBot && aiomaticIsNumeric(defaultBot))
2709
+
{
2710
+
aiomatic_chat_ajax_object.bots_data.forEach((relement) => {
2711
+
if(relement.ID == defaultBot)
2712
+
{
2713
+
matchedBotID = relement.ID;
2714
+
matchedBotName = relement.name;
2715
+
matchedBotPrompt = relement.prompt;
2716
+
matchedBotModel = relement.model;
2717
+
matchedBotAssistantID = relement.assistentid;
2718
+
responded = ' aiomatic-ainum-' + matchedBotID;
2719
+
}});
2720
+
}
2721
+
}
2722
+
matchedBots = aiomatic_chat_ajax_object.bots_data.filter(bot => {
2723
+
const nameWithoutSpaces = bot.name.replace(/\s+/g, '');
2724
+
return input_text.includes(`@${bot.name}`) || input_text.includes(`@${nameWithoutSpaces}`);
2725
+
});
2726
+
if (matchedBots.length > 0)
2727
+
{
2728
+
const matchedBot = matchedBots[0];
2729
+
matchedBotID = matchedBot.ID;
2730
+
matchedBotName = matchedBot.name;
2731
+
matchedBotPrompt = matchedBot.prompt;
2732
+
matchedBotModel = matchedBot.model;
2733
+
matchedBotAssistantID = matchedBot.assistentid;
2734
+
responded = ' aiomatic-ainum-' + matchedBotID;
2735
+
}
2736
+
}
2737
+
var displayed_scroll = false;
2738
+
window.addEventListener('scroll', function () {
2739
+
if(displayed_scroll === false)
2740
+
{
2741
+
const scrollTop = window.scrollY || window.pageYOffset;
2742
+
const windowHeight = window.innerHeight;
2743
+
const docHeight = Math.max(
2744
+
document.body.scrollHeight, document.documentElement.scrollHeight,
2745
+
document.body.offsetHeight, document.documentElement.offsetHeight,
2746
+
document.body.clientHeight, document.documentElement.clientHeight
2747
+
);
2748
+
2749
+
const scrolledPercent = (scrollTop + windowHeight) / docHeight * 100;
2750
+
2751
+
if (scrolledPercent >= scrollPercent) {
2752
+
const chatbotContainer = document.getElementById('openai-ai-chat-form-' + instance);
2753
+
const chatstyle = window.getComputedStyle(chatbotContainer);
2754
+
if (chatstyle.display === 'none' || chatstyle.visibility === 'hidden' || chatstyle.opacity === '0') {
2755
+
displayed_scroll = true;
2756
+
bot_displayed = true;
2757
+
$('#aiomatic-open-button' + instance).click();
2758
+
if (chatOnce) {
2759
+
localStorage.setItem(storageKey_scroll, '1');
2760
+
}
2761
+
if(window["aiomatic_chat_ajax_object" + instance].page_scroll_chat_message != '')
2762
+
{
2763
+
aiomaticDisplayBotMessage(window["aiomatic_chat_ajax_object" + instance].page_scroll_chat_message, instance, window["aiomatic_chat_ajax_object" + instance], responded, aiomatic_chat_ajax_object.instant_response, aiomatic_chat_ajax_object.persistent, 1000);
2764
+
}
2765
+
}
2766
+
}
2767
+
}
2768
+
});
2769
+
}
2770
+
}
2771
+
}
2772
+
}
2773
+
if(bot_displayed == false)
2774
+
{
2775
+
if(window["aiomatic_chat_ajax_object" + instance].page_inactive_chat == '1')
2776
+
{
2777
+
var aiomatic_chat_ajax_object = window["aiomatic_chat_ajax_object" + instance];
2778
+
const chatOnce = window["aiomatic_chat_ajax_object" + instance].page_inactive_chat_once == '1';
2779
+
const inactiveTime = parseInt(aiomatic_chat_ajax_object.page_inactive_chat_time) || 30000;
2780
+
const storageKey_inactive = "aiomatic_chat_autoloaded_inactive";
2781
+
if (!chatOnce || !localStorage.getItem(storageKey_inactive))
2782
+
{
2783
+
const allowedUrlsRaw = window["aiomatic_chat_ajax_object" + instance].page_inactive_chat_urls || '';
2784
+
const allowedUrls = allowedUrlsRaw
2785
+
.split('\n')
2786
+
.map(url => url.trim())
2787
+
.filter(url => url.length > 0);
2788
+
2789
+
const currentUrl = window.location.href;
2790
+
const shouldAutoload =
2791
+
allowedUrls.length === 0 ||
2792
+
allowedUrls.some(url => currentUrl.includes(url));
2793
+
2794
+
if (shouldAutoload) {
2795
+
var responded = '';
2796
+
if(aiomatic_chat_ajax_object.bots_data)
2797
+
{
2798
+
var matchedBots = [];
2799
+
var defaultBot = jQuery('#aiomatic_default_hidden_' + instance);
2800
+
if(defaultBot)
2801
+
{
2802
+
defaultBot = defaultBot.val();
2803
+
if(defaultBot && aiomaticIsNumeric(defaultBot))
2804
+
{
2805
+
aiomatic_chat_ajax_object.bots_data.forEach((relement) => {
2806
+
if(relement.ID == defaultBot)
2807
+
{
2808
+
matchedBotID = relement.ID;
2809
+
matchedBotName = relement.name;
2810
+
matchedBotPrompt = relement.prompt;
2811
+
matchedBotModel = relement.model;
2812
+
matchedBotAssistantID = relement.assistentid;
2813
+
responded = ' aiomatic-ainum-' + matchedBotID;
2814
+
}});
2815
+
}
2816
+
}
2817
+
matchedBots = aiomatic_chat_ajax_object.bots_data.filter(bot => {
2818
+
const nameWithoutSpaces = bot.name.replace(/\s+/g, '');
2819
+
return input_text.includes(`@${bot.name}`) || input_text.includes(`@${nameWithoutSpaces}`);
2820
+
});
2821
+
if (matchedBots.length > 0)
2822
+
{
2823
+
const matchedBot = matchedBots[0];
2824
+
matchedBotID = matchedBot.ID;
2825
+
matchedBotName = matchedBot.name;
2826
+
matchedBotPrompt = matchedBot.prompt;
2827
+
matchedBotModel = matchedBot.model;
2828
+
matchedBotAssistantID = matchedBot.assistentid;
2829
+
responded = ' aiomatic-ainum-' + matchedBotID;
2830
+
}
2831
+
}
2832
+
var displayed_inactive = false;
2833
+
let inactivityTimer;
2834
+
2835
+
function startInactivityTimer() {
2836
+
clearTimeout(inactivityTimer);
2837
+
inactivityTimer = setTimeout(() => {
2838
+
if (displayed_inactive) return;
2839
+
2840
+
const chatbotContainer = document.getElementById('openai-ai-chat-form-' + instance);
2841
+
const chatstyle = window.getComputedStyle(chatbotContainer);
2842
+
2843
+
if (chatstyle.display === 'none' || chatstyle.visibility === 'hidden' || chatstyle.opacity === '0') {
2844
+
displayed_inactive = true;
2845
+
bot_displayed = true;
2846
+
2847
+
$('#aiomatic-open-button' + instance).click();
2848
+
2849
+
if (chatOnce) {
2850
+
localStorage.setItem(storageKey_inactive, '1');
2851
+
}
2852
+
2853
+
if (aiomatic_chat_ajax_object.page_inactive_chat_message !== '') {
2854
+
aiomaticDisplayBotMessage(
2855
+
aiomatic_chat_ajax_object.page_inactive_chat_message,
2856
+
instance,
2857
+
aiomatic_chat_ajax_object,
2858
+
responded,
2859
+
aiomatic_chat_ajax_object.instant_response,
2860
+
aiomatic_chat_ajax_object.persistent,
2861
+
1000
2862
+
);
2863
+
}
2864
+
}
2865
+
}, inactiveTime);
2866
+
}
2867
+
2868
+
startInactivityTimer();
2869
+
2870
+
['mousemove', 'keydown', 'scroll', 'touchstart'].forEach(evt => {
2871
+
document.addEventListener(evt, startInactivityTimer, { passive: true });
2872
+
});
2873
+
}
2874
+
}
2875
+
}
2876
+
}
2877
+
if(window["aiomatic_chat_ajax_object" + instance].chat_editing === 'all' || window["aiomatic_chat_ajax_object" + instance].chat_editing === 'user')
2878
+
{
2879
+
$(document).on("click", ".aiomatic_chat_history .ai-bubble.ai-mine", function () {
2880
+
const $bubble = $(this);
2881
+
$bubble.attr("contenteditable", "true").focus();
2882
+
});
2883
+
$(document).on("blur", ".aiomatic_chat_history .ai-bubble.ai-mine", function () {
2884
+
const $bubble = $(this);
2885
+
$bubble.attr("contenteditable", "false");
2886
+
});
2887
+
$(document).on("keydown", ".aiomatic_chat_history .ai-bubble.ai-mine", function (e) {
2888
+
if (e.key === "Enter") {
2889
+
e.preventDefault();
2890
+
$(this).blur();
2891
+
}
2892
+
});
2893
+
$(document).on("mouseenter", ".aiomatic_chat_history .ai-bubble.ai-mine", function () {
2894
+
$(this).css("cursor", "pointer");
2895
+
});
2896
+
}
2897
+
if(window["aiomatic_chat_ajax_object" + instance].chat_editing === 'all' || window["aiomatic_chat_ajax_object" + instance].chat_editing === 'chatbot')
2898
+
{
2899
+
$(document).on("click", ".aiomatic_chat_history .ai-bubble.ai-other", function () {
2900
+
const $bubble = $(this);
2901
+
$bubble.attr("contenteditable", "true").focus();
2902
+
});
2903
+
$(document).on("blur", ".aiomatic_chat_history .ai-bubble.ai-other", function () {
2904
+
const $bubble = $(this);
2905
+
$bubble.attr("contenteditable", "false");
2906
+
});
2907
+
$(document).on("keydown", ".aiomatic_chat_history .ai-bubble.ai-other", function (e) {
2908
+
if (e.key === "Enter") {
2909
+
e.preventDefault();
2910
+
$(this).blur();
2911
+
}
2912
+
});
2913
+
$(document).on("mouseenter", ".aiomatic_chat_history .ai-bubble.ai-other", function () {
2914
+
$(this).css("cursor", "pointer");
2915
+
});
2916
+
}
2917
+
if(window["aiomatic_chat_ajax_object" + instance].show_gdpr === '1')
2918
+
{
2919
+
document.getElementById('aiomatic-start-chatting-button' + instance).addEventListener('click', function() {
2920
+
const consentCheckbox = document.getElementById('aiomatic-consent-checkbox' + instance);
2921
+
if (consentCheckbox.checked)
2922
+
{
2923
+
localStorage.setItem('chatbotConsent' + chatID, 'true');
2924
+
aiomatic_toggleOverlay(instance, chatID);
2925
+
} else {
2926
+
alert('Please agree to the terms to continue.');
2927
+
}
2928
+
});
2929
+
document.getElementById('aiomatic-consent-checkbox' + instance).addEventListener('change', function() {
2930
+
const startButton = document.getElementById('aiomatic-start-chatting-button' + instance);
2931
+
startButton.disabled = !this.checked;
2932
+
});
2933
+
window.onload = function() {
2934
+
aiomatic_toggleOverlay(instance, chatID);
2935
+
};
2936
+
}
2937
+
jQuery('body').on('click', '#aivisionbut' + instance, function(e)
2938
+
{
2939
+
$('#aiomatic_vision_input' + instance).click();
2940
+
});
2941
+
jQuery('body').on('change', '#aiomatic_vision_input' + instance, function(e)
2942
+
{
2943
+
var vision_input = jQuery('#aiomatic_vision_input' + instance);
2944
+
if (vision_input[0] !== undefined && vision_input[0].files !== undefined && vision_input[0].files[0] !== undefined && vision_input[0].files && vision_input[0].files[0])
2945
+
{
2946
+
$('#aivisionbut' + instance).css("background-color", window["aiomatic_chat_ajax_object" + instance].bg_color);
2947
+
}
2948
+
else
2949
+
{
2950
+
$('#aivisionbut' + instance).css("background-color", "");
2951
+
}
2952
+
});
2953
+
});
2954
+
});
2955
+
function aiomatic_esc_html(unsafe)
2956
+
{
2957
+
return unsafe
2958
+
.replace(/&/g, '&')
2959
+
.replace(/</g, '<')
2960
+
.replace(/>/g, '>')
2961
+
.replace(/"/g, '"')
2962
+
.replace(/'/g, ''');
2963
+
}
2964
+
function aiomatic_parseMarkdown(text)
2965
+
{
2966
+
text = text.replace(/(<br\s*\/?>\s*){2,}/gi, '<br>');
2967
+
// Headers
2968
+
text = text.replace(/^###### (.+?)$/gm, '<h6>$1</h6>');
2969
+
text = text.replace(/^##### (.+?)$/gm, '<h5>$1</h5>');
2970
+
text = text.replace(/^#### (.+?)$/gm, '<h4>$1</h4>');
2971
+
text = text.replace(/^### (.+?)$/gm, '<h3>$1</h3>');
2972
+
text = text.replace(/^## (.+?)$/gm, '<h2>$1</h2>');
2973
+
text = text.replace(/^# (.+?)$/gm, '<h1>$1</h1>');
2974
+
2975
+
// Bold
2976
+
text = text.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
2977
+
text = text.replace(/__(.+?)__/g, '<strong>$1</strong>');
2978
+
2979
+
// Italic
2980
+
text = text.replace(/([^\*])\*([^\*]+?)\*/gs, '$1<em>$2</em>');
2981
+
text = text.replace(/([^_])_([^_]+?)_/gs, '$1<em>$2</em>');
2982
+
2983
+
// Strikethrough
2984
+
text = text.replace(/~~(.+?)~~/g, '<del>$1</del>');
2985
+
2986
+
// Inline Code
2987
+
text = text.replace(/([^`])`([^`]+?)`/g, '$1<code>$2</code>');
2988
+
2989
+
// Code Block
2990
+
text = text.replace(/```([\s\S]+?)```/g, '<code>$1</code>');
2991
+
2992
+
// Link
2993
+
text = text.replace(/\[(.+?)\]\((.+?)\)/g, '<a href="$2">$1</a>');
2994
+
2995
+
// Images
2996
+
text = text.replace(/!\[(.+?)\]\((.+?)\)/g, '<img src="$2" alt="$1">');
2997
+
2998
+
// Horizontal Rule
2999
+
text = text.replace(/^-{3,}$/gm, '<hr>');
3000
+
3001
+
// Blockquote
3002
+
text = text.replace(/^> (.+?)$/gm, '<blockquote>$1</blockquote>');
3003
+
3004
+
return text;
3005
+
}
3006
+
function aiomatic_nl2br (str, is_xhtml) {
3007
+
if (typeof str === 'undefined' || str === null) {
3008
+
return '';
3009
+
}
3010
+
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
3011
+
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
3012
+
}
3013
+
function aiomatic_mergeDeep(target, source)
3014
+
{
3015
+
Object.keys(source).forEach(key =>
3016
+
{
3017
+
if (source[key] && typeof source[key] === 'object' && key !== 'arguments')
3018
+
{
3019
+
if (!target[key])
3020
+
{
3021
+
target[key] = {};
3022
+
}
3023
+
aiomatic_mergeDeep(target[key], source[key]);
3024
+
}
3025
+
else
3026
+
{
3027
+
if (key === 'arguments')
3028
+
{
3029
+
if (!target[key])
3030
+
{
3031
+
target[key] = '';
3032
+
}
3033
+
target[key] += source[key];
3034
+
}
3035
+
else
3036
+
{
3037
+
target[key] = source[key];
3038
+
}
3039
+
}
3040
+
});
3041
+
}
3042
+
function aiomaticEscapeHtml(text) {
3043
+
var map = {
3044
+
'&': '&',
3045
+
'<': '<',
3046
+
'>': '>',
3047
+
'"': '"',
3048
+
"'": '''
3049
+
};
3050
+
return text.replace(/[&<>"']/g, function(m) { return map[m]; });
3051
+
}
3052
+
function aiChatUploadDataomatic(aiomatic_chat_ajax_object, uniqid, input_text, remember_string, user_question, function_result)
3053
+
{
3054
+
var formData = new FormData();
3055
+
formData.append('uniqid', uniqid);
3056
+
formData.append('input_text', input_text);
3057
+
formData.append('remember_string', remember_string);
3058
+
formData.append('user_question', user_question);
3059
+
if(function_result !== null)
3060
+
{
3061
+
formData.append('function_result', function_result);
3062
+
}
3063
+
formData.append('action', 'aiomatic_save_chat_data');
3064
+
formData.append('nonce', aiomatic_chat_ajax_object.persistentnonce);
3065
+
return jQuery.ajax({
3066
+
url: aiomatic_chat_ajax_object.ajax_url,
3067
+
async: false,
3068
+
type: 'POST',
3069
+
data: formData,
3070
+
contentType: false,
3071
+
processData: false
3072
+
});
3073
+
};
3074
+
function aiomaticaddConversationStarters(conversationStarters, instance)
3075
+
{
3076
+
const starterContainer = document.getElementById("aiomatic-conversation-starters" + instance);
3077
+
if (!starterContainer) {
3078
+
console.error("Conversation starters container not found.");
3079
+
return;
3080
+
}
3081
+
conversationStarters = conversationStarters.split(";");
3082
+
starterContainer.innerHTML = "";
3083
+
starterContainer.style.display = "flex";
3084
+
starterContainer.style.justifyContent = "center";
3085
+
starterContainer.style.gap = "10px";
3086
+
starterContainer.style.marginTop = "10px";
3087
+
starterContainer.style.marginBottom = "10px";
3088
+
conversationStarters.forEach((starter) =>
3089
+
{
3090
+
const starterElement = document.createElement("div");
3091
+
starterElement.className = "aiomatic-conversation-starter";
3092
+
starterElement.textContent = starter;
3093
+
starterElement.addEventListener("click", () => {
3094
+
aiomaticaddUserMessage(starter, instance);
3095
+
});
3096
+
starterContainer.appendChild(starterElement);
3097
+
});
3098
+
jQuery('body').on('click', '#aichatsubmitbut' + instance, aiomaticHideConversationStartersClickHandler(instance));
3099
+
}
3100
+
function aiomaticaddUserMessage(message, instance)
3101
+
{
3102
+
var $chatInput = jQuery('#aiomatic_chat_input' + instance);
3103
+
if ($chatInput.length > 0)
3104
+
{
3105
+
$chatInput.val(message);
3106
+
jQuery('#aichatsubmitbut' + instance).click();
3107
+
}
3108
+
}
3109
+
function aiomaticLoading(btn)
3110
+
{
3111
+
btn.attr('disabled','disabled');
3112
+
if(!btn.find('aiomatic-jumping-dots').length){
3113
+
btn.append('<span class="aiomatic-jumping-dots"> <span class="aiomatic-dot-1">.</span><span class="aiomatic-dot-2">.</span><span class="aiomatic-dot-3">.</span></span>');
3114
+
}
3115
+
btn.find('.aiomatic-jumping-dots').css('visibility','unset');
3116
+
}
3117
+
function processKatexMarkdown(text)
3118
+
{
3119
+
text = text.replace(/(\\\[)([\s\S]*?)(\\\])/g, (match, start, content, end) => {
3120
+
const cleanedContent = content.replace(/<br\s*\/?>/gi, '');
3121
+
return `${start}${cleanedContent}${end}`;
3122
+
});
3123
+
return text;
3124
+
}
3125
+
function initChatbotAiomatic(instance)
3126
+
{
3127
+
String.prototype.aitrim = function()
3128
+
{
3129
+
return this.replace(/^\s+|\s+$/g, "");
3130
+
};
3131
+
function aiomaticHideAndRepair(chatbut, e, instance)
3132
+
{
3133
+
aiomaticRmLoading(chatbut)
3134
+
var chatbut = jQuery('#aiomatic-video-wrapper' + instance);
3135
+
chatbut.hide();
3136
+
streamingEpicFail = true;
3137
+
console.error('Failed to init D-ID stream: ', e);
3138
+
alert('Chatbot avatar failed to load, please try again later.');
3139
+
}
3140
+
var aiomatic_chat_ajax_object = window["aiomatic_chat_ajax_object" + instance];
3141
+
if(aiomatic_chat_ajax_object.conversation_starters && aiomatic_chat_ajax_object.conversation_starters != '')
3142
+
{
3143
+
const conversationStarters = aiomatic_chat_ajax_object.conversation_starters;
3144
+
aiomaticaddConversationStarters(conversationStarters, instance);
3145
+
}
3146
+
3147
+
var streamingEpicFail = false;
3148
+
var avatarImageUrl = '';
3149
+
var did_app_id = '';
3150
+
var azure_speech_id = '';
3151
+
if(aiomatic_chat_ajax_object.updown_navigate == '1')
3152
+
{
3153
+
var $chatInput = jQuery('#aiomatic_chat_input' + instance);
3154
+
if ($chatInput.length > 0)
3155
+
{
3156
+
var aiomaticChatHistory = [];
3157
+
var aiomaticCurrentIndex = -1;
3158
+
var storageKey = `chat_history_${instance}`;
3159
+
var savedHistory = sessionStorage.getItem(storageKey);
3160
+
if (savedHistory) {
3161
+
try
3162
+
{
3163
+
aiomaticChatHistory = JSON.parse(savedHistory);
3164
+
}
3165
+
catch (errorSpeech){
3166
+
console.log('Exception init chatbot: ' + errorSpeech);
3167
+
}
3168
+
}
3169
+
$chatInput.on('keydown', function(event) {
3170
+
if (event.key === "ArrowUp") {
3171
+
if (aiomaticCurrentIndex > 0) {
3172
+
aiomaticCurrentIndex--;
3173
+
$chatInput.val(aiomaticChatHistory[aiomaticCurrentIndex]);
3174
+
}
3175
+
event.preventDefault();
3176
+
} else if (event.key === "ArrowDown") {
3177
+
if (aiomaticCurrentIndex < aiomaticChatHistory.length - 1) {
3178
+
aiomaticCurrentIndex++;
3179
+
$chatInput.val(aiomaticChatHistory[aiomaticCurrentIndex]);
3180
+
} else {
3181
+
aiomaticCurrentIndex = aiomaticChatHistory.length;
3182
+
$chatInput.val('');
3183
+
}
3184
+
event.preventDefault();
3185
+
}
3186
+
});
3187
+
}
3188
+
}
3189
+
if(aiomatic_chat_ajax_object.persistent == 'history')
3190
+
{
3191
+
document.body.addEventListener("click", function (evt)
3192
+
{
3193
+
var logsdrop = document.querySelector('#chat-logs-dropdown' + instance);
3194
+
var toggleButton = document.querySelector('#aihistorybut' + instance);
3195
+
if (logsdrop && logsdrop.style.display !== "none")
3196
+
{
3197
+
if (!logsdrop.contains(evt.target) && !toggleButton.contains(evt.target))
3198
+
{
3199
+
aiomatic_hide_chat_logs(instance);
3200
+
}
3201
+
}
3202
+
});
3203
+
}
3204
+
if(aiomatic_chat_ajax_object.text_speech == 'didstream' && !jQuery('.aiomatic-gg-unmute').length)
3205
+
{
3206
+
avatarImageUrl = aiomatic_chat_ajax_object.did_image;
3207
+
did_app_id = aiomatic_chat_ajax_object.did_app_id;
3208
+
if(avatarImageUrl != '' && did_app_id != '')
3209
+
{
3210
+
var chatbut = jQuery('#aichatsubmitbut' + instance);
3211
+
aiomaticLoading(chatbut);
3212
+
myStreamObject.startAndDisplayStream(avatarImageUrl, instance, did_app_id).catch((e) => aiomaticHideAndRepair(chatbut, e, instance));
3213
+
}
3214
+
}
3215
+
if(aiomatic_chat_ajax_object.text_speech == 'azure' && !jQuery('.aiomatic-gg-unmute').length)
3216
+
{
3217
+
azure_speech_id = aiomatic_chat_ajax_object.azure_speech_id;
3218
+
var privateEndpoint = aiomatic_chat_ajax_object.azure_private_endpoint;
3219
+
var customVoiceEndpointId = aiomatic_chat_ajax_object.azure_voice_endpoint;
3220
+
var cogSvcRegion = aiomatic_chat_ajax_object.azure_region;
3221
+
var talkingAvatarCharacter = aiomatic_chat_ajax_object.azure_character;
3222
+
var talkingAvatarStyle = aiomatic_chat_ajax_object.azure_character_style;
3223
+
3224
+
if(azure_speech_id != '')
3225
+
{
3226
+
try
3227
+
{
3228
+
window.onload = function() {
3229
+
document.body.addEventListener('click', function() {
3230
+
var chatbut = jQuery('#aichatsubmitbut' + instance);
3231
+
aiomaticLoading(chatbut);
3232
+
azureStartAndDisplayStream(instance, azure_speech_id, cogSvcRegion, privateEndpoint, customVoiceEndpointId, talkingAvatarCharacter, talkingAvatarStyle);
3233
+
aiomaticRmLoading(chatbut, instance);
3234
+
}, { once: true });
3235
+
};
3236
+
}
3237
+
catch(error)
3238
+
{
3239
+
console.error("An error occurred while streaming using Azure: " + error);
3240
+
}
3241
+
}
3242
+
}
3243
+
jQuery(document).on('click', '#ai-export-txt' + instance, function (event)
3244
+
{
3245
+
event.preventDefault();
3246
+
ai_chat_download();
3247
+
});
3248
+
jQuery(document).on('click', '#ai-clear-chat' + instance, function (event)
3249
+
{
3250
+
event.preventDefault();
3251
+
jQuery('#aiomatic_chat_history' + instance).html('');
3252
+
});
3253
+
jQuery(document).on('click', '.aiomatic-gg-mute', function() {
3254
+
jQuery(this).removeClass('aiomatic-gg-mute').addClass('aiomatic-gg-unmute');
3255
+
});
3256
+
jQuery(document).on('click', '.aiomatic-gg-unmute', function() {
3257
+
jQuery(this).removeClass('aiomatic-gg-unmute').addClass('aiomatic-gg-mute');
3258
+
});
3259
+
jQuery(document).on('click', '.aiomatic-gg-globalist', function()
3260
+
{
3261
+
var chatid = jQuery('.aiomatic-gg-globalist').attr('chatid');
3262
+
var jq = jQuery('#aiomatic-globe-overlay' + chatid);
3263
+
jq.toggleClass('aiomatic-globe-bar');
3264
+
var title = 'Disable Chatbot Internet Access' ;
3265
+
if(jq.hasClass('aiomatic-globe-bar'))
3266
+
{
3267
+
title = 'Enable Chatbot Internet Access';
3268
+
}
3269
+
jQuery('#aiomatic-globe-overlay-mother' + chatid).attr('title', title);
3270
+
});
3271
+
jQuery(document).on('click', '#aichatsubmitbut' + instance, function (event)
3272
+
{
3273
+
event.preventDefault();
3274
+
openaichatfunct().catch(console.error);
3275
+
});
3276
+
jQuery('body').on('click', '#aipdfbut' + instance, function(e)
3277
+
{
3278
+
jQuery('#aiomatic_pdf_input' + instance).click();
3279
+
});
3280
+
jQuery('body').on('click', '#aifilebut' + instance, function(e)
3281
+
{
3282
+
jQuery('#aiomatic_file_input' + instance).click();
3283
+
});
3284
+
var aiomatic_generator_working = false;
3285
+
var eventGenerator = false;
3286
+
jQuery('body').on('click', '#aistopbut' + instance, function(e)
3287
+
{
3288
+
var chatbut = jQuery('#aichatsubmitbut' + instance);
3289
+
aiomaticRmLoading(chatbut, instance);
3290
+
aiomatic_generator_working = false;
3291
+
eventGenerator.close();
3292
+
jQuery('#aistopbut' + instance).hide();
3293
+
});
3294
+
jQuery('body').on('change', '#aiomatic_pdf_input' + instance, async function(e)
3295
+
{
3296
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status"> </div>');
3297
+
var pdf_input = jQuery('#aiomatic_pdf_input' + instance);
3298
+
if(pdf_input !== null && pdf_input !== undefined)
3299
+
{
3300
+
if (pdf_input[0] !== undefined && pdf_input[0].files !== undefined && pdf_input[0].files[0] !== undefined && pdf_input[0].files && pdf_input[0].files[0])
3301
+
{
3302
+
var pdfIcon = document.getElementById('aipdfbut' + instance);
3303
+
var originalIcon = pdfIcon.innerHTML;
3304
+
pdfIcon.innerHTML = '<div class="aiomatic-pdf-loading"></div>';
3305
+
jQuery('body').off('click', '#aipdfbut' + instance);
3306
+
var emb_namespace = 'pdf_' + Math.ceil(Math.random() * 100000);
3307
+
var formData = new FormData();
3308
+
formData.append('image', pdf_input[0].files[0]);
3309
+
formData.append('pdf_namespace', emb_namespace);
3310
+
formData.append('action', 'aiomatic_handle_chat_pdf_upload');
3311
+
formData.append('nonce', aiomatic_chat_ajax_object.persistentnonce);
3312
+
await jQuery.ajax({
3313
+
url: aiomatic_chat_ajax_object.ajax_url,
3314
+
type: 'POST',
3315
+
data: formData,
3316
+
contentType: false,
3317
+
processData: false,
3318
+
success: function(response)
3319
+
{
3320
+
if(response.status == 'success')
3321
+
{
3322
+
pdf_input.val('');
3323
+
const chatx = document.getElementById('aichatsubmitbut' + instance);
3324
+
chatx.setAttribute('data-pdf', emb_namespace);
3325
+
pdfIcon.innerHTML = '<div class="aiomatic-pdf-remove">×</div>';
3326
+
pdfIcon.title = "End PDF session";
3327
+
jQuery('body').on('click', '#aipdfbut' + instance, function(e)
3328
+
{
3329
+
const chatx = document.getElementById('aichatsubmitbut' + instance);
3330
+
chatx.setAttribute('data-pdf', '');
3331
+
jQuery('body').off('click', '#aipdfbut' + instance);
3332
+
pdfIcon.innerHTML = originalIcon;
3333
+
pdfIcon.title = "Upload a PDF file to the chatbot";
3334
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.pdf_end + '</div>');
3335
+
jQuery('body').on('click', '#aipdfbut' + instance, function(e)
3336
+
{
3337
+
jQuery('#aiomatic_pdf_input' + instance).click();
3338
+
});
3339
+
});
3340
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.pdf_ok + '</div>');
3341
+
}
3342
+
else
3343
+
{
3344
+
pdf_input.val('');
3345
+
console.log(JSON.stringify(response));
3346
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.pdf_fail + '</div>');
3347
+
pdfIcon.innerHTML = originalIcon;
3348
+
return;
3349
+
}
3350
+
},
3351
+
error: function(error) {
3352
+
pdf_input.val('');
3353
+
console.log('Error while calling pdf upload functions: ' + error.responseText);
3354
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.pdf_fail + '</div>');
3355
+
pdfIcon.innerHTML = originalIcon;
3356
+
return;
3357
+
}
3358
+
});
3359
+
}
3360
+
}
3361
+
});
3362
+
3363
+
jQuery('body').on('change', '#aiomatic_file_input' + instance, async function(e)
3364
+
{
3365
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status"> </div>');
3366
+
var file_input = jQuery('#aiomatic_file_input' + instance);
3367
+
if(file_input !== null && file_input !== undefined)
3368
+
{
3369
+
if (file_input[0] !== undefined && file_input[0].files !== undefined && file_input[0].files[0] !== undefined && file_input[0].files && file_input[0].files[0])
3370
+
{
3371
+
var fileIcon = document.getElementById('aifilebut' + instance);
3372
+
var ai_thread_id = jQuery('#aiomatic_thread_id' + instance).val();
3373
+
var originalIcon = fileIcon.innerHTML;
3374
+
fileIcon.innerHTML = '<div class="aiomatic-file-loading"></div>';
3375
+
jQuery('body').off('click', '#aifilebut' + instance);
3376
+
var formData = new FormData();
3377
+
formData.append('image', file_input[0].files[0]);
3378
+
formData.append('thread_id', ai_thread_id);
3379
+
formData.append('action', 'aiomatic_handle_chat_file_upload');
3380
+
formData.append('nonce', aiomatic_chat_ajax_object.persistentnonce);
3381
+
await jQuery.ajax({
3382
+
url: aiomatic_chat_ajax_object.ajax_url,
3383
+
type: 'POST',
3384
+
data: formData,
3385
+
contentType: false,
3386
+
processData: false,
3387
+
success: function(response)
3388
+
{
3389
+
if(response.status == 'success')
3390
+
{
3391
+
file_input.val('');
3392
+
const chatx = document.getElementById('aichatsubmitbut' + instance);
3393
+
chatx.setAttribute('data-store', response.msg);
3394
+
chatx.setAttribute('data-file', response.fid);
3395
+
fileIcon.innerHTML = '<div class="aiomatic-file-remove">×</div>';
3396
+
fileIcon.title = "End file session";
3397
+
jQuery('body').on('click', '#aifilebut' + instance, async function(e)
3398
+
{
3399
+
const chatx = document.getElementById('aichatsubmitbut' + instance);
3400
+
fileIcon.innerHTML = '<div class="aiomatic-file-loading"></div>';
3401
+
var delstore = chatx.getAttribute('data-store');
3402
+
var delfile = chatx.getAttribute('data-file');
3403
+
if(delfile != '')
3404
+
{
3405
+
var formDelData = new FormData();
3406
+
formDelData.append('id', delfile);
3407
+
formDelData.append('storeid', delstore);
3408
+
formDelData.append('action', 'aiomatic_delete_assistant_vector_store');
3409
+
formDelData.append('nonce', aiomatic_chat_ajax_object.nonce);
3410
+
await jQuery.ajax({
3411
+
url: aiomatic_chat_ajax_object.ajax_url,
3412
+
type: 'POST',
3413
+
data: formDelData,
3414
+
contentType: false,
3415
+
processData: false,
3416
+
success: function(response)
3417
+
{
3418
+
console.log('File deleted');
3419
+
},
3420
+
error: function(error) {
3421
+
console.log('Failed to delete file ID: ' + delfile + ', error: ' + error.responseText);
3422
+
}
3423
+
});
3424
+
}
3425
+
chatx.setAttribute('data-file', '');
3426
+
chatx.setAttribute('data-store', '');
3427
+
jQuery('body').off('click', '#aifilebut' + instance);
3428
+
fileIcon.innerHTML = originalIcon;
3429
+
fileIcon.title = "Upload a file to the chatbot";
3430
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.file_end + '</div>');
3431
+
jQuery('body').on('click', '#aifilebut' + instance, function(e)
3432
+
{
3433
+
jQuery('#aiomatic_file_input' + instance).click();
3434
+
});
3435
+
});
3436
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.file_ok + '</div>');
3437
+
}
3438
+
else
3439
+
{
3440
+
file_input.val('');
3441
+
console.log(JSON.stringify(response));
3442
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.file_fail + '</div>');
3443
+
fileIcon.innerHTML = originalIcon;
3444
+
return;
3445
+
}
3446
+
},
3447
+
error: function(error) {
3448
+
file_input.val('');
3449
+
console.log('Error while calling file upload functions: ' + error.responseText);
3450
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.file_fail + '</div>');
3451
+
fileIcon.innerHTML = originalIcon;
3452
+
return;
3453
+
}
3454
+
});
3455
+
}
3456
+
}
3457
+
});
3458
+
function aiisAlphaNumeric(str) {
3459
+
var code, i, len;
3460
+
for (i = 0, len = str.length; i < len; i++) {
3461
+
code = str.charCodeAt(i);
3462
+
if (!(code > 47 && code < 58) && // numeric (0-9)
3463
+
!(code > 64 && code < 91) && // upper alpha (A-Z)
3464
+
!(code > 96 && code < 123)) { // lower alpha (a-z)
3465
+
return false;
3466
+
}
3467
+
}
3468
+
return true;
3469
+
}
3470
+
var input = document.getElementById("aiomatic_chat_input" + instance);
3471
+
if(input !== undefined && input !== null)
3472
+
{
3473
+
input.addEventListener("keydown", function (e) {
3474
+
if (e.key === "Enter" && !e.shiftKey) {
3475
+
e.preventDefault();
3476
+
var chatbut = jQuery('#aichatsubmitbut' + instance);
3477
+
if (!chatbut.is(':disabled')) {
3478
+
var xstarter = jQuery('#aiomatic-conversation-starters' + instance);
3479
+
if(xstarter)
3480
+
{
3481
+
xstarter.hide();
3482
+
}
3483
+
openaichatfunct().catch(console.error);
3484
+
return false;
3485
+
}
3486
+
}
3487
+
});
3488
+
}
3489
+
function airemovePrefix(mainString, substring)
3490
+
{
3491
+
if (mainString.startsWith(substring))
3492
+
{
3493
+
return mainString.slice(substring.length);
3494
+
} else
3495
+
{
3496
+
return mainString;
3497
+
}
3498
+
}
3499
+
function airemoveAfter(mainString, substring) {
3500
+
var index = mainString.indexOf(substring);
3501
+
if (index !== -1) {
3502
+
return mainString.slice(0, index);
3503
+
} else {
3504
+
return mainString;
3505
+
}
3506
+
}
3507
+
function AiHtmlDecode(input) {
3508
+
var doc = new DOMParser().parseFromString(input, "text/html");
3509
+
return doc.documentElement.textContent;
3510
+
}
3511
+
function ai_trimHtmlToMaxLength(htmlString, maxLength)
3512
+
{
3513
+
const parser = new DOMParser();
3514
+
const doc = parser.parseFromString(htmlString, 'text/html');
3515
+
const divs = doc.querySelectorAll('div');
3516
+
for (let i = divs.length - 1; i >= 0; i--)
3517
+
{
3518
+
if (doc.body.innerHTML.length <= maxLength)
3519
+
{
3520
+
break;
3521
+
}
3522
+
divs[i].parentNode.removeChild(divs[i]);
3523
+
}
3524
+
return doc.body.innerHTML;
3525
+
}
3526
+
function ai_chat_download()
3527
+
{
3528
+
if(aiomatic_chat_ajax_object.chat_download_format == 'txt')
3529
+
{
3530
+
var x_input_text = jQuery('#aiomatic_chat_history' + instance).html();
3531
+
var text = x_input_text.replace(/<div class="ai-wrapper"><div class="ai-bubble ai-other"[^>]*?>([\s\S]*?)<\/div><\/div>/g, aiomatic_chat_ajax_object.ai_message_preppend + "$1\n");
3532
+
text = text.replace(/<div class="ai-wrapper"><div class="ai-bubble ai-mine"[^>]*?>([\s\S]*?)<\/div><\/div>/g, aiomatic_chat_ajax_object.user_message_preppend + "$1\n");
3533
+
text = text.replace(/<div class="ai-avatar ai-mine"[^>]*?><\/div>/g, "");
3534
+
text = text.replace(/<div class="ai-avatar ai-other(?: aiomatic-ainum-\d+)?"[^>]*?><\/div>/g, "");
3535
+
text = text.replace(/<div class="ai-speech"[^>]*?>([\s\S]*?)<\/div>/g, '');
3536
+
text = text.aitrim();
3537
+
var element = document.createElement('a');
3538
+
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
3539
+
element.setAttribute('download', 'chat.txt');
3540
+
element.style.display = 'none';
3541
+
document.body.appendChild(element);
3542
+
element.click();
3543
+
document.body.removeChild(element);
3544
+
}
3545
+
else
3546
+
{
3547
+
var element = document.querySelector('#aiomatic_chat_history' + instance);
3548
+
var originalStyle = element.getAttribute('style');
3549
+
element.style.height = 'auto';
3550
+
element.style.maxHeight = 'none';
3551
+
element.style.overflow = 'visible';
3552
+
html2canvas(element, {
3553
+
scrollY: -window.scrollY,
3554
+
useCORS: true,
3555
+
windowWidth: element.scrollWidth,
3556
+
windowHeight: element.scrollHeight
3557
+
}).then(canvas =>
3558
+
{
3559
+
const imgData = canvas.toDataURL('image/png');
3560
+
const { jsPDF } = window.jspdf;
3561
+
const pdf = new jsPDF({
3562
+
orientation: 'landscape',
3563
+
unit: 'px',
3564
+
format: [canvas.width, canvas.height]
3565
+
});
3566
+
var pageHeight = pdf.internal.pageSize.height;
3567
+
var imgHeight = canvas.height;
3568
+
var heightLeft = imgHeight;
3569
+
var position = 0;
3570
+
pdf.addImage(imgData, 'PNG', 0, position, canvas.width, canvas.height);
3571
+
heightLeft -= pageHeight;
3572
+
while (heightLeft >= 0)
3573
+
{
3574
+
position = heightLeft - imgHeight;
3575
+
pdf.addImage(imgData, 'PNG', 0, position, canvas.width, canvas.height);
3576
+
heightLeft -= pageHeight;
3577
+
}
3578
+
pdf.save('chat.pdf');
3579
+
element.setAttribute('style', originalStyle);
3580
+
});
3581
+
}
3582
+
}
3583
+
function aiomatic_strstr(haystack, needle, bool)
3584
+
{
3585
+
var pos = 0;
3586
+
haystack += "";
3587
+
pos = haystack.indexOf(needle); if (pos == -1) {
3588
+
return false;
3589
+
} else {
3590
+
if (bool) {
3591
+
return haystack.substr(0, pos);
3592
+
} else {
3593
+
return haystack.slice(pos);
3594
+
}
3595
+
}
3596
+
}
3597
+
function aiomaticIsNumeric(n)
3598
+
{
3599
+
return !isNaN(parseFloat(n)) && isFinite(n);
3600
+
}
3601
+
async function openaichatfunct()
3602
+
{
3603
+
var chatbut = jQuery('#aichatsubmitbut' + instance);
3604
+
aiomaticLoading(chatbut);
3605
+
var input_textj = jQuery('#aiomatic_chat_input' + instance);
3606
+
var ai_thread_id = jQuery('#aiomatic_thread_id' + instance).val();
3607
+
var ai_assistant_id = jQuery('#aiomatic_assistant_id' + instance).val();
3608
+
if(ai_assistant_id === null)
3609
+
{
3610
+
ai_assistant_id = '';
3611
+
}
3612
+
var pdf_data = chatbut.attr('data-pdf');
3613
+
if(pdf_data === undefined || pdf_data === null)
3614
+
{
3615
+
pdf_data = '';
3616
+
}
3617
+
var file_data = chatbut.attr('data-store');
3618
+
if(file_data === undefined || file_data === null)
3619
+
{
3620
+
file_data = '';
3621
+
}
3622
+
var input_text = '';
3623
+
if(aiomatic_chat_ajax_object.text_speech == 'did' && !jQuery('.aiomatic-gg-unmute').length)
3624
+
{
3625
+
const boxes = document.querySelectorAll('.ai_video');
3626
+
boxes.forEach(box => {
3627
+
box.remove();
3628
+
});
3629
+
}
3630
+
input_text = input_textj.val();
3631
+
if(aiomatic_chat_ajax_object.no_empty == '1' && input_text == '')
3632
+
{
3633
+
aiomaticRmLoading(chatbut, instance);
3634
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.message_required + '</div>');
3635
+
return;
3636
+
}
3637
+
if(aiomatic_chat_ajax_object.updown_navigate == '1')
3638
+
{
3639
+
aiomaticChatHistory.push(input_text);
3640
+
aiomaticCurrentIndex = aiomaticChatHistory.length;
3641
+
sessionStorage.setItem(`chat_history_${instance}`, JSON.stringify(aiomaticChatHistory));
3642
+
}
3643
+
var responded = '';
3644
+
var matchedBotID = '';
3645
+
var matchedBotName = '';
3646
+
var matchedBotPrompt = '';
3647
+
var matchedBotModel = '';
3648
+
var matchedBotAssistantID = '';
3649
+
var matchedBots = [];
3650
+
var model = aiomatic_chat_ajax_object.model;
3651
+
var temp = aiomatic_chat_ajax_object.temp;
3652
+
var top_p = aiomatic_chat_ajax_object.top_p;
3653
+
var presence = aiomatic_chat_ajax_object.presence;
3654
+
var frequency = aiomatic_chat_ajax_object.frequency;
3655
+
var store_data = aiomatic_chat_ajax_object.store_data;
3656
+
var instant_response = aiomatic_chat_ajax_object.instant_response;
3657
+
var user_token_cap_per_day = aiomatic_chat_ajax_object.user_token_cap_per_day;
3658
+
var user_id = aiomatic_chat_ajax_object.user_id;
3659
+
var enable_god_mode = aiomatic_chat_ajax_object.enable_god_mode;
3660
+
var mcp_servers = aiomatic_chat_ajax_object.mcp_servers;
3661
+
var persistent = aiomatic_chat_ajax_object.persistent;
3662
+
if (model.startsWith('gpt-5-pro') && instant_response === 'stream') {
3663
+
instant_response = 'on';
3664
+
}
3665
+
3666
+
input_text = aiomaticEscapeHtml(input_text);
3667
+
if(aiomatic_chat_ajax_object.blocked_words != '')
3668
+
{
3669
+
let blocked_words = aiomatic_chat_ajax_object.blocked_words.split(',');
3670
+
if (blocked_words.length > 0) {
3671
+
blocked_words.forEach(blockedWord => {
3672
+
let regex = new RegExp(`\\b${blockedWord.trim()}\\b`, 'gi');
3673
+
input_text = input_text.replace(regex, match => '*'.repeat(match.length));
3674
+
});
3675
+
}
3676
+
}
3677
+
if(aiomatic_chat_ajax_object.bots_data)
3678
+
{
3679
+
var defaultBot = jQuery('#aiomatic_default_hidden_' + instance);
3680
+
if(defaultBot)
3681
+
{
3682
+
defaultBot = defaultBot.val();
3683
+
if(defaultBot && aiomaticIsNumeric(defaultBot))
3684
+
{
3685
+
aiomatic_chat_ajax_object.bots_data.forEach((relement) => {
3686
+
if(relement.ID == defaultBot)
3687
+
{
3688
+
matchedBotID = relement.ID;
3689
+
matchedBotName = relement.name;
3690
+
matchedBotPrompt = relement.prompt;
3691
+
matchedBotModel = relement.model;
3692
+
matchedBotAssistantID = relement.assistentid;
3693
+
responded = ' aiomatic-ainum-' + matchedBotID;
3694
+
}});
3695
+
}
3696
+
}
3697
+
matchedBots = aiomatic_chat_ajax_object.bots_data.filter(bot => {
3698
+
const nameWithoutSpaces = bot.name.replace(/\s+/g, '');
3699
+
return input_text.includes(`@${bot.name}`) || input_text.includes(`@${nameWithoutSpaces}`);
3700
+
});
3701
+
if (matchedBots.length > 0)
3702
+
{
3703
+
const matchedBot = matchedBots[0];
3704
+
matchedBotID = matchedBot.ID;
3705
+
matchedBotName = matchedBot.name;
3706
+
matchedBotPrompt = matchedBot.prompt;
3707
+
matchedBotModel = matchedBot.model;
3708
+
matchedBotAssistantID = matchedBot.assistentid;
3709
+
responded = ' aiomatic-ainum-' + matchedBotID;
3710
+
}
3711
+
}
3712
+
if(matchedBotID !== '')
3713
+
{
3714
+
ai_assistant_id = matchedBotAssistantID;
3715
+
}
3716
+
var user_question = input_text;
3717
+
input_textj.val('');
3718
+
if(aiomatic_chat_ajax_object.enable_moderation == '1')
3719
+
{
3720
+
var isflagged = false;
3721
+
await jQuery.ajax({
3722
+
type: 'POST',
3723
+
url: aiomatic_chat_ajax_object.ajax_url,
3724
+
data: {
3725
+
action: 'aiomatic_moderate_text',
3726
+
text: input_text,
3727
+
nonce: aiomatic_chat_ajax_object.moderation_nonce,
3728
+
model: aiomatic_chat_ajax_object.moderation_model
3729
+
},
3730
+
success: function(response) {
3731
+
if(typeof response === 'string' || response instanceof String)
3732
+
{
3733
+
try
3734
+
{
3735
+
var responset = JSON.parse(response);
3736
+
response = responset;
3737
+
}
3738
+
catch (error)
3739
+
{
3740
+
console.error("An error occurred while parsing the JSON: " + error + ' Json: ' + response);
3741
+
}
3742
+
}
3743
+
if(response.status == 'success')
3744
+
{
3745
+
var resp = null;
3746
+
try
3747
+
{
3748
+
resp = JSON.parse(response.data);
3749
+
}
3750
+
catch (error)
3751
+
{
3752
+
console.error("An error occurred while parsing the JSON: " + error + ' Json: ' + resp);
3753
+
}
3754
+
if(resp.results[0].flagged != undefined)
3755
+
{
3756
+
if(resp.results[0].flagged == true)
3757
+
{
3758
+
aiomaticRmLoading(chatbut, instance);
3759
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.flagged_message + '</div>');
3760
+
isflagged = true;
3761
+
}
3762
+
}
3763
+
else
3764
+
{
3765
+
console.log('Invalid response from moderation ' + response);
3766
+
}
3767
+
}
3768
+
else
3769
+
{
3770
+
if(typeof response.msg !== 'undefined')
3771
+
{
3772
+
console.log('Moderation returned an error: ' + response.msg);
3773
+
}
3774
+
else
3775
+
{
3776
+
console.log('Moderation returned an error: ' + response);
3777
+
}
3778
+
}
3779
+
},
3780
+
error: function(error) {
3781
+
console.log('Moderation failed: ' + error.responseText);
3782
+
},
3783
+
});
3784
+
if(isflagged == true)
3785
+
{
3786
+
return;
3787
+
}
3788
+
}
3789
+
var chat_preppend_text = aiomatic_chat_ajax_object.chat_preppend_text;
3790
+
if(matchedBotID !== '')
3791
+
{
3792
+
chat_preppend_text = matchedBotPrompt;
3793
+
}
3794
+
var user_message_preppend = aiomatic_chat_ajax_object.user_message_preppend;
3795
+
var ai_message_preppend = aiomatic_chat_ajax_object.ai_message_preppend;
3796
+
if(matchedBotID !== '')
3797
+
{
3798
+
if(matchedBotName == '')
3799
+
{
3800
+
ai_message_preppend = '';
3801
+
}
3802
+
else
3803
+
{
3804
+
ai_message_preppend = matchedBotName + ':';
3805
+
}
3806
+
}
3807
+
var x_input_text = jQuery('#aiomatic_chat_history' + instance).html();
3808
+
var remember_string = x_input_text;
3809
+
var is_modern_gpt = aiomatic_chat_ajax_object.is_modern_gpt;
3810
+
if(aiomatic_chat_ajax_object.max_messages != '')
3811
+
{
3812
+
const regex = /(<div class="ai-bubble ai-other"[^>]*?>[\s\S]*?<\/div>)|(<div class="ai-bubble ai-mine"[^>]*?>[\s\S]*?<\/div>)|(<div class="ai-speech"[^>]*?>[\s\S]*?<\/div>)/g;
3813
+
let matches = [];
3814
+
let match;
3815
+
while ((match = regex.exec(remember_string)) !== null) {
3816
+
matches.push(match[0]);
3817
+
}
3818
+
remember_string = matches.slice(0 - parseInt(aiomatic_chat_ajax_object.max_messages)).join('');
3819
+
}
3820
+
if(aiomatic_chat_ajax_object.max_message_context != '')
3821
+
{
3822
+
if(remember_string.length > parseInt(aiomatic_chat_ajax_object.max_message_context))
3823
+
{
3824
+
remember_string = ai_trimHtmlToMaxLength(remember_string, parseInt(aiomatic_chat_ajax_object.max_message_context));
3825
+
}
3826
+
}
3827
+
if(is_modern_gpt == '1')
3828
+
{
3829
+
remember_string = aiomatic_parse_html_to_gptobj(remember_string);
3830
+
if(chat_preppend_text != '')
3831
+
{
3832
+
remember_string.unshift({ role: 'system', content: chat_preppend_text });
3833
+
}
3834
+
remember_string = JSON.stringify(remember_string);
3835
+
}
3836
+
else
3837
+
{
3838
+
remember_string = remember_string.replace(/<div class="ai-avatar ai-mine"[^>]*?><\/div>/g, "");
3839
+
remember_string = remember_string.replace(/<div class="ai-avatar ai-other(?:\s+aiomatic-ainum-\d+)?"[^>]*?><\/div>/g, "");
3840
+
remember_string = remember_string.replace(/<div class="ai-speech"[^>]*?>([\s\S]*?)<\/div>/g, '');
3841
+
remember_string = remember_string.replace(/<div class="ai-wrapper"><div class="ai-bubble ai-other"[^>]*?>([\s\S]*?)<\/div><\/div>/g, ai_message_preppend + "$1\n");
3842
+
remember_string = remember_string.replace(/<div class="ai-wrapper"><div class="ai-bubble ai-mine"[^>]*?>([\s\S]*?)<\/div><\/div>/g, user_message_preppend + "$1\n");
3843
+
remember_string = remember_string.replace(/<div class="ai-bubble ai-other"[^>]*?>([\s\S]*?)<\/div>/g, ai_message_preppend + "$1\n");
3844
+
remember_string = remember_string.replace(/<div class="ai-bubble ai-mine"[^>]*?>([\s\S]*?)<\/div>/g, user_message_preppend + "$1\n");
3845
+
remember_string = remember_string.aitrim();
3846
+
remember_string = remember_string.slice(-12000);
3847
+
var nlregex = /<br\s*[\/]?>/gi;
3848
+
remember_string = remember_string.replace(nlregex, "\n");
3849
+
if(chat_preppend_text != '')
3850
+
{
3851
+
remember_string = chat_preppend_text + '\n' + remember_string;
3852
+
}
3853
+
}
3854
+
const user_lang = navigator.language || navigator.userLanguage;
3855
+
remember_string = remember_string.replace(/%%user_language%%/g, user_lang);
3856
+
if(ai_assistant_id != '')
3857
+
{
3858
+
if(persistent != 'off' && persistent != '0' && persistent != '')
3859
+
{
3860
+
persistent = 'assistant';
3861
+
}
3862
+
}
3863
+
if(model == 'default' || model == '')
3864
+
{
3865
+
model = jQuery( "#model-chat-selector" + instance + " option:selected" ).text();
3866
+
}
3867
+
if(matchedBotID !== '')
3868
+
{
3869
+
model = matchedBotModel;
3870
+
}
3871
+
if(temp == 'default' || temp == '')
3872
+
{
3873
+
temp = jQuery('#temperature-chat-input' + instance).val();
3874
+
}
3875
+
if(top_p == 'default' || top_p == '')
3876
+
{
3877
+
top_p = jQuery('#top_p-chat-input' + instance).val();
3878
+
}
3879
+
if(presence == 'default' || presence == '')
3880
+
{
3881
+
presence = jQuery('#presence-chat-input' + instance).val();
3882
+
}
3883
+
if(frequency == 'default' || frequency == '')
3884
+
{
3885
+
frequency = jQuery('#frequency-chat-input' + instance).val();
3886
+
}
3887
+
var vision_file = '';
3888
+
var vision_input = jQuery('#aiomatic_vision_input' + instance);
3889
+
if(vision_input !== null && vision_input !== undefined)
3890
+
{
3891
+
if (vision_input[0] !== undefined && vision_input[0].files !== undefined && vision_input[0].files[0] !== undefined && vision_input[0].files && vision_input[0].files[0])
3892
+
{
3893
+
var formData = new FormData();
3894
+
formData.append('image', vision_input[0].files[0]);
3895
+
formData.append('action', 'aiomatic_handle_vision_image_upload');
3896
+
formData.append('nonce', aiomatic_chat_ajax_object.persistentnonce);
3897
+
await jQuery.ajax({
3898
+
url: aiomatic_chat_ajax_object.ajax_url,
3899
+
type: 'POST',
3900
+
data: formData,
3901
+
contentType: false,
3902
+
processData: false,
3903
+
success: function(response)
3904
+
{
3905
+
if(response.status == 'success')
3906
+
{
3907
+
if(response.image_url !== '')
3908
+
{
3909
+
vision_input.val('');
3910
+
jQuery('#aivisionbut' + instance).css("background-color", "");
3911
+
vision_file = response.image_url;
3912
+
}
3913
+
else
3914
+
{
3915
+
vision_input.val('');
3916
+
jQuery('#aivisionbut' + instance).css("background-color", "");
3917
+
aiomaticRmLoading(chatbut, instance);
3918
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.file_fail + '</div>');
3919
+
return;
3920
+
}
3921
+
}
3922
+
else
3923
+
{
3924
+
vision_input.val('');
3925
+
jQuery('#aivisionbut' + instance).css("background-color", "");
3926
+
aiomaticRmLoading(chatbut, instance);
3927
+
console.log(JSON.stringify(response));
3928
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + response.msg + '</div>');
3929
+
return;
3930
+
}
3931
+
},
3932
+
error: function(error) {
3933
+
vision_input.val('');
3934
+
jQuery('#aivisionbut' + instance).css("background-color", "");
3935
+
console.log('Error while calling AI functions: ' + error.responseText);
3936
+
aiomaticRmLoading(chatbut, instance);
3937
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.file_fail + '</div>');
3938
+
return;
3939
+
}
3940
+
});
3941
+
}
3942
+
}
3943
+
if(input_text.aitrim() != '')
3944
+
{
3945
+
if(aiomatic_chat_ajax_object.send_message_sound != '')
3946
+
{
3947
+
var snd = new Audio(aiomatic_chat_ajax_object.send_message_sound);
3948
+
snd.play();
3949
+
}
3950
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status"> </div>');
3951
+
input_text = input_text.replace(/(?:\r\n|\r|\n)/g, '<br>');
3952
+
var appendhtml = '<div class="ai-wrapper">';
3953
+
if(aiomatic_chat_ajax_object.bubble_user_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url_user != '' && aiomatic_chat_ajax_object.show_user_avatar == 'show')
3954
+
{
3955
+
appendhtml += '<div class="ai-avatar ai-mine"></div>';
3956
+
}
3957
+
appendhtml += '<div class="ai-bubble ai-mine">' + input_text;
3958
+
if(vision_file != '')
3959
+
{
3960
+
appendhtml += '<img src="' + vision_file + '" class="aiomatic-vision-image">';
3961
+
}
3962
+
appendhtml += '</div>';
3963
+
if(aiomatic_chat_ajax_object.bubble_user_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url_user != '' && aiomatic_chat_ajax_object.show_user_avatar == 'show')
3964
+
{
3965
+
appendhtml += '<div class="ai-avatar ai-mine"></div>';
3966
+
}
3967
+
appendhtml += '</div>';
3968
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
3969
+
appendhtml = processKatexMarkdown(appendhtml);
3970
+
}
3971
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
3972
+
appendhtml = aiomatic_parseMarkdown(appendhtml);
3973
+
}
3974
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendhtml);
3975
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
3976
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
3977
+
renderMathInElement(katexContainer, {
3978
+
delimiters: [
3979
+
3980
+
{ left: '\\(', right: '\\)', display: false },
3981
+
{ left: '\\[', right: '\\]', display: true }
3982
+
],
3983
+
throwOnError: false
3984
+
});
3985
+
}
3986
+
}
3987
+
if(aiomatic_chat_ajax_object.response_delay.trim() != '')
3988
+
{
3989
+
let xms;
3990
+
var sleepval = aiomatic_chat_ajax_object.response_delay.trim();
3991
+
if (typeof sleepval === 'string' && sleepval.includes('-'))
3992
+
{
3993
+
const [min, max] = sleepval.split('-').map(Number);
3994
+
xms = Math.floor(Math.random() * (max - min + 1)) + min;
3995
+
}
3996
+
else
3997
+
{
3998
+
xms = Number(sleepval);
3999
+
}
4000
+
await aiomaticSleep(xms);
4001
+
}
4002
+
var input_text_raw = input_text;
4003
+
var lastch = input_text.charAt(input_text.length - 1);
4004
+
if(aiisAlphaNumeric(lastch))
4005
+
{
4006
+
input_text += '.';
4007
+
}
4008
+
if(user_message_preppend != '')
4009
+
{
4010
+
var endSpace = /\s$/;
4011
+
if (endSpace.test(user_message_preppend))
4012
+
{
4013
+
input_text = user_message_preppend + input_text;
4014
+
}
4015
+
else
4016
+
{
4017
+
input_text = user_message_preppend + ' ' + input_text;
4018
+
}
4019
+
}
4020
+
if(is_modern_gpt != '1')
4021
+
{
4022
+
if(ai_message_preppend != '')
4023
+
{
4024
+
input_text = input_text + ' \n' + ai_message_preppend;
4025
+
}
4026
+
}
4027
+
if( jQuery('#aiomatic_message_input'+ instance).length )
4028
+
{
4029
+
var hardcoded_chat = jQuery('#aiomatic_message_input' + instance).val();
4030
+
if(hardcoded_chat !== '')
4031
+
{
4032
+
const fm = hardcoded_chat.trim().split(/\\r\\n|\\r|\\n/).filter(xline => xline.length > 0);
4033
+
if(fm[0] !== undefined && fm[0] !== null)
4034
+
{
4035
+
var x_input_text = jQuery('#aiomatic_chat_history' + instance).html();
4036
+
var hardresponse = fm[0];
4037
+
fm.shift();
4038
+
if(fm.length == 0 && aiomatic_strstr(x_input_text, hardresponse, false) !== false)
4039
+
{
4040
+
hardresponse = false;
4041
+
}
4042
+
while(aiomatic_strstr(x_input_text, hardresponse, false) !== false && fm.length > 0)
4043
+
{
4044
+
fm.shift();
4045
+
if(fm.length > 0)
4046
+
{
4047
+
hardresponse = fm[0];
4048
+
}
4049
+
else
4050
+
{
4051
+
hardresponse = false;
4052
+
break;
4053
+
}
4054
+
}
4055
+
if(fm.length > 0)
4056
+
{
4057
+
jQuery('#aiomatic_message_input' + instance).val(fm.join('\\r\\n'));
4058
+
}
4059
+
else
4060
+
{
4061
+
jQuery('#aiomatic_message_input' + instance).val('');
4062
+
}
4063
+
if(hardresponse !== false)
4064
+
{
4065
+
aiomaticDisplayBotMessage(hardresponse, instance, aiomatic_chat_ajax_object, responded, instant_response, persistent, 1000);
4066
+
return;
4067
+
}
4068
+
}
4069
+
}
4070
+
}
4071
+
const userId = aiomaticgetOrCreateUserId();
4072
+
const { conversationEnded, actionPerformed } = await aiomaticProcessUserMessage(userId, input_text_raw, instance, aiomatic_chat_ajax_object, responded, instant_response, persistent);
4073
+
if (conversationEnded) {
4074
+
aiomaticRmLoading(chatbut, instance);
4075
+
jQuery('#aiomatic_chat_input' + instance).prop('disabled', true);
4076
+
jQuery('#aichatsubmitbut' + instance).prop('disabled', true);
4077
+
if(jQuery('#openai-chat-speech-button' + instance))
4078
+
{
4079
+
jQuery('#openai-chat-speech-button' + instance).prop('disabled', true);
4080
+
}
4081
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.conversation_ended + '</div>');
4082
+
return;
4083
+
}
4084
+
var user_state = aiomaticGetUserState(userId);
4085
+
if(user_state && user_state.prompt)
4086
+
{
4087
+
if(is_modern_gpt == '1')
4088
+
{
4089
+
var new_remember_string = '';
4090
+
try
4091
+
{
4092
+
new_remember_string = JSON.parse(remember_string);
4093
+
}
4094
+
catch (errorSpeech){
4095
+
console.log('Exception rememberstring: ' + errorSpeech);
4096
+
}
4097
+
if(new_remember_string && new_remember_string[0] && new_remember_string[0].content)
4098
+
{
4099
+
new_remember_string[0].content = user_state.prompt + ' ' + new_remember_string[0].content;
4100
+
remember_string = JSON.stringify(new_remember_string);
4101
+
}
4102
+
else
4103
+
{
4104
+
if (typeof remember_string === 'string' || remember_string instanceof String)
4105
+
{
4106
+
remember_string = user_state.prompt + ' ' + remember_string;
4107
+
}
4108
+
}
4109
+
}
4110
+
else
4111
+
{
4112
+
if (typeof remember_string === 'string' || remember_string instanceof String)
4113
+
{
4114
+
remember_string = user_state.prompt + ' ' + remember_string;
4115
+
}
4116
+
}
4117
+
}
4118
+
if (!actionPerformed)
4119
+
{
4120
+
if(instant_response == 'stream')
4121
+
{
4122
+
if(aiomatic_generator_working === true)
4123
+
{
4124
+
console.log('AI Chatbot already working!');
4125
+
aiomaticRmLoading(chatbut, instance);
4126
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
4127
+
return;
4128
+
}
4129
+
if(ai_assistant_id != '' && ai_thread_id == '')
4130
+
{
4131
+
await jQuery.ajax({
4132
+
type: 'POST',
4133
+
url: aiomatic_chat_ajax_object.ajax_url,
4134
+
data: {
4135
+
action: 'aiomatic_create_thread',
4136
+
nonce: aiomatic_chat_ajax_object.nonce,
4137
+
assistantid: ai_assistant_id,
4138
+
file_data: file_data
4139
+
},
4140
+
success: function(result)
4141
+
{
4142
+
if(result.status == 'success' && result.data != undefined)
4143
+
{
4144
+
jQuery('#aiomatic_thread_id' + instance).val(result.data);
4145
+
ai_thread_id = result.data;
4146
+
}
4147
+
else
4148
+
{
4149
+
console.log('Thread creation failed: ' + JSON.stringify(result));
4150
+
}
4151
+
},
4152
+
error: function(error) {
4153
+
console.log('Failed to create thread: ' + error.responseText);
4154
+
},
4155
+
});
4156
+
}
4157
+
if(enable_god_mode == '')
4158
+
{
4159
+
enable_god_mode = 'off';
4160
+
}
4161
+
aiomatic_generator_working = true;
4162
+
var count_line = 0;
4163
+
var response_data = '';
4164
+
var internet_permission = aiomatic_chat_ajax_object.internet_access;
4165
+
if(jQuery('#aiomatic-globe-overlay' + instance).hasClass('aiomatic-globe-bar') && jQuery('#aiomatic-globe-overlay' + instance).is(':visible'))
4166
+
{
4167
+
internet_permission = 'disabled';
4168
+
}
4169
+
var eventURL = aiomatic_chat_ajax_object.stream_url;
4170
+
if(aiomatic_chat_ajax_object.bots_data && aiomatic_chat_ajax_object.strip_botname == '1')
4171
+
{
4172
+
aiomatic_chat_ajax_object.bots_data.forEach((relement) => input_text = input_text.replace('@' + relement.name, ''));
4173
+
}
4174
+
eventURL += '&input_text=' + encodeURIComponent(input_text);
4175
+
if(pdf_data != '')
4176
+
{
4177
+
eventURL += '&pdf_data=' + encodeURIComponent(pdf_data);
4178
+
}
4179
+
if(file_data != '')
4180
+
{
4181
+
eventURL += '&file_data=' + encodeURIComponent(file_data);
4182
+
}
4183
+
if(aiomatic_chat_ajax_object.user_token_cap_per_day != '')
4184
+
{
4185
+
eventURL += '&user_token_cap_per_day=' + encodeURIComponent(aiomatic_chat_ajax_object.user_token_cap_per_day);
4186
+
}
4187
+
if(aiomatic_chat_ajax_object.user_id != '')
4188
+
{
4189
+
eventURL += '&user_id=' + encodeURIComponent(aiomatic_chat_ajax_object.user_id);
4190
+
}
4191
+
if(aiomatic_chat_ajax_object.frequency != '')
4192
+
{
4193
+
eventURL += '&frequency=' + encodeURIComponent(aiomatic_chat_ajax_object.frequency);
4194
+
}
4195
+
if(aiomatic_chat_ajax_object.store_data != '')
4196
+
{
4197
+
eventURL += '&store_data=' + encodeURIComponent(aiomatic_chat_ajax_object.store_data);
4198
+
}
4199
+
if(aiomatic_chat_ajax_object.presence != '')
4200
+
{
4201
+
eventURL += '&presence=' + encodeURIComponent(aiomatic_chat_ajax_object.presence);
4202
+
}
4203
+
if(aiomatic_chat_ajax_object.top_p != '')
4204
+
{
4205
+
eventURL += '&top_p=' + encodeURIComponent(aiomatic_chat_ajax_object.top_p);
4206
+
}
4207
+
if(aiomatic_chat_ajax_object.temp != '')
4208
+
{
4209
+
eventURL += '&temp=' + encodeURIComponent(aiomatic_chat_ajax_object.temp);
4210
+
}
4211
+
if(aiomatic_chat_ajax_object.model != '')
4212
+
{
4213
+
eventURL += '&model=' + encodeURIComponent(aiomatic_chat_ajax_object.model);
4214
+
}
4215
+
if(ai_assistant_id != '')
4216
+
{
4217
+
eventURL += '&assistant_id=' + encodeURIComponent(ai_assistant_id);
4218
+
}
4219
+
if(ai_thread_id != '')
4220
+
{
4221
+
eventURL += '&thread_id=' + encodeURIComponent(ai_thread_id);
4222
+
}
4223
+
if(user_lang != '')
4224
+
{
4225
+
eventURL += '&user_lang=' + encodeURIComponent(user_lang);
4226
+
}
4227
+
if(remember_string != '')
4228
+
{
4229
+
eventURL += '&remember_string=' + encodeURIComponent(remember_string);
4230
+
}
4231
+
if(is_modern_gpt != '')
4232
+
{
4233
+
eventURL += '&is_modern_gpt=' + encodeURIComponent(is_modern_gpt);
4234
+
}
4235
+
if(internet_permission != '')
4236
+
{
4237
+
eventURL += '&internet_access=' + encodeURIComponent(internet_permission);
4238
+
}
4239
+
if(aiomatic_chat_ajax_object.embeddings != '')
4240
+
{
4241
+
eventURL += '&embeddings=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings);
4242
+
}
4243
+
if(aiomatic_chat_ajax_object.embeddings_namespace != '')
4244
+
{
4245
+
eventURL += '&embeddings_namespace=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings_namespace);
4246
+
}
4247
+
if(user_question != '')
4248
+
{
4249
+
eventURL += '&user_question=' + encodeURIComponent(user_question);
4250
+
}
4251
+
if(enable_god_mode != '')
4252
+
{
4253
+
eventURL += '&enable_god_mode=' + encodeURIComponent(enable_god_mode);
4254
+
}
4255
+
if(mcp_servers != '')
4256
+
{
4257
+
eventURL += '&mcp_servers=' + encodeURIComponent(mcp_servers);
4258
+
}
4259
+
if(vision_file != '')
4260
+
{
4261
+
eventURL += '&vision_file=' + encodeURIComponent(vision_file);
4262
+
}
4263
+
if(eventURL.length > 2080)
4264
+
{
4265
+
console.log('URL too long, using alternative event method');
4266
+
var unid = "id" + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
4267
+
aiChatUploadDataomatic(aiomatic_chat_ajax_object, unid, input_text, remember_string, user_question, null);
4268
+
eventURL = aiomatic_chat_ajax_object.stream_url + '&input_text=0&remember_string=0&user_question=0';
4269
+
if(pdf_data != '')
4270
+
{
4271
+
eventURL += '&pdf_data=' + encodeURIComponent(pdf_data);
4272
+
}
4273
+
if(file_data != '')
4274
+
{
4275
+
eventURL += '&file_data=' + encodeURIComponent(file_data);
4276
+
}
4277
+
if(aiomatic_chat_ajax_object.user_token_cap_per_day != '')
4278
+
{
4279
+
eventURL += '&user_token_cap_per_day=' + encodeURIComponent(aiomatic_chat_ajax_object.user_token_cap_per_day);
4280
+
}
4281
+
if(aiomatic_chat_ajax_object.user_id != '')
4282
+
{
4283
+
eventURL += '&user_id=' + encodeURIComponent(aiomatic_chat_ajax_object.user_id);
4284
+
}
4285
+
if(aiomatic_chat_ajax_object.frequency != '')
4286
+
{
4287
+
eventURL += '&frequency=' + encodeURIComponent(aiomatic_chat_ajax_object.frequency);
4288
+
}
4289
+
if(aiomatic_chat_ajax_object.store_data != '')
4290
+
{
4291
+
eventURL += '&store_data=' + encodeURIComponent(aiomatic_chat_ajax_object.store_data);
4292
+
}
4293
+
if(aiomatic_chat_ajax_object.presence != '')
4294
+
{
4295
+
eventURL += '&presence=' + encodeURIComponent(aiomatic_chat_ajax_object.presence);
4296
+
}
4297
+
if(aiomatic_chat_ajax_object.top_p != '')
4298
+
{
4299
+
eventURL += '&top_p=' + encodeURIComponent(aiomatic_chat_ajax_object.top_p);
4300
+
}
4301
+
if(aiomatic_chat_ajax_object.temp != '')
4302
+
{
4303
+
eventURL += '&temp=' + encodeURIComponent(aiomatic_chat_ajax_object.temp);
4304
+
}
4305
+
if(aiomatic_chat_ajax_object.model != '')
4306
+
{
4307
+
eventURL += '&model=' + encodeURIComponent(aiomatic_chat_ajax_object.model);
4308
+
}
4309
+
if(ai_assistant_id != '')
4310
+
{
4311
+
eventURL += '&assistant_id=' + encodeURIComponent(ai_assistant_id);
4312
+
}
4313
+
if(ai_thread_id != '')
4314
+
{
4315
+
eventURL += '&thread_id=' + encodeURIComponent(ai_thread_id);
4316
+
}
4317
+
if(is_modern_gpt != '')
4318
+
{
4319
+
eventURL += '&is_modern_gpt=' + encodeURIComponent(is_modern_gpt);
4320
+
}
4321
+
if(internet_permission != '')
4322
+
{
4323
+
eventURL += '&internet_access=' + encodeURIComponent(internet_permission);
4324
+
}
4325
+
if(aiomatic_chat_ajax_object.embeddings != '')
4326
+
{
4327
+
eventURL += '&embeddings=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings);
4328
+
}
4329
+
if(aiomatic_chat_ajax_object.embeddings_namespace != '')
4330
+
{
4331
+
eventURL += '&embeddings_namespace=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings_namespace);
4332
+
}
4333
+
if(enable_god_mode != '')
4334
+
{
4335
+
eventURL += '&enable_god_mode=' + encodeURIComponent(enable_god_mode);
4336
+
}
4337
+
if(mcp_servers != '')
4338
+
{
4339
+
eventURL += '&mcp_servers=' + encodeURIComponent(mcp_servers);
4340
+
}
4341
+
eventURL += '&bufferid=' + encodeURIComponent(unid);
4342
+
if(vision_file != '')
4343
+
{
4344
+
eventURL += '&vision_file=' + encodeURIComponent(vision_file);
4345
+
}
4346
+
}
4347
+
try
4348
+
{
4349
+
eventGenerator = new EventSource(eventURL);
4350
+
}
4351
+
catch(e)
4352
+
{
4353
+
console.log('Error in Event creation: ' + e);
4354
+
}
4355
+
eventGenerator.onopen = function() {
4356
+
jQuery('#aistopbut' + instance).show();
4357
+
};
4358
+
var initialContent = jQuery('#aiomatic_chat_history' + instance).html();
4359
+
var error_generated = '';
4360
+
var func_call = {
4361
+
init_data: {
4362
+
pdf_data: pdf_data,
4363
+
file_data: file_data,
4364
+
user_token_cap_per_day: aiomatic_chat_ajax_object.user_token_cap_per_day,
4365
+
user_id: aiomatic_chat_ajax_object.user_id,
4366
+
store_data: aiomatic_chat_ajax_object.store_data,
4367
+
frequency: aiomatic_chat_ajax_object.frequency,
4368
+
presence: aiomatic_chat_ajax_object.presence,
4369
+
top_p: aiomatic_chat_ajax_object.top_p,
4370
+
temp: aiomatic_chat_ajax_object.temp,
4371
+
model: aiomatic_chat_ajax_object.model,
4372
+
input_text: input_text,
4373
+
remember_string: remember_string,
4374
+
is_modern_gpt: is_modern_gpt,
4375
+
user_question: user_question
4376
+
},
4377
+
};
4378
+
function handleContentBlockDeltaResponses(e)
4379
+
{
4380
+
var aiomatic_newline_before = false;
4381
+
var aiomatic_response_events = 0;
4382
+
var aiomatic_limitLines = 1;
4383
+
var currentContent = jQuery('#aiomatic_chat_history' + instance).html();
4384
+
var resultData = null;
4385
+
var content_generated = '';
4386
+
var hasFinishReason = false;
4387
+
var error_generated = '';
4388
+
if (e.type === 'response.output_text.delta' || e.type === 'response.completed' || e.type === 'response.failed' || e.type === 'response.incomplete') {
4389
+
try {
4390
+
resultData = JSON.parse(e.data);
4391
+
} catch (err) {
4392
+
console.warn('Failed to parse OpenAI event data: ' + err);
4393
+
aiomaticRmLoading(chatbut, instance);
4394
+
aiomatic_generator_working = false;
4395
+
eventGenerator.close();
4396
+
jQuery('#aistopbut' + instance).hide();
4397
+
return;
4398
+
}
4399
+
4400
+
if (e.type === 'response.output_text.delta') {
4401
+
content_generated = resultData.delta || '';
4402
+
aiomatic_response_events += 1;
4403
+
} else if (e.type === 'response.completed') {
4404
+
hasFinishReason = true;
4405
+
content_generated = '';
4406
+
} else if (e.type === 'response.failed') {
4407
+
error_generated = resultData.response.error?.message || 'Unknown error';
4408
+
console.log('OpenAI Response failed: ' + error_generated);
4409
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + error_generated + '</div>');
4410
+
eventGenerator.close();
4411
+
jQuery('#aistopbut' + instance).hide();
4412
+
aiomaticRmLoading(chatbut, instance);
4413
+
aiomatic_generator_working = false;
4414
+
return;
4415
+
} else if (e.type === 'response.incomplete') {
4416
+
hasFinishReason = true;
4417
+
error_generated = 'Response incomplete: ' + (resultData.response.incomplete_details?.reason || 'unknown reason');
4418
+
console.warn(error_generated);
4419
+
}
4420
+
}
4421
+
4422
+
if (error_generated === '' && content_generated !== '') {
4423
+
if(aiomatic_chat_ajax_object.enable_html != true)
4424
+
{
4425
+
content_generated = aiomatic_esc_html(content_generated);
4426
+
}
4427
+
response_data += aiomatic_nl2br(content_generated);
4428
+
if(aiomatic_chat_ajax_object.strip_js == true)
4429
+
{
4430
+
response_data = response_data.replace(/<script[\s\S]*?<\/script>/gi, '');
4431
+
response_data = response_data.replace(/on\w+="[^"]*"/gi, '');
4432
+
}
4433
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
4434
+
response_data = processKatexMarkdown(response_data);
4435
+
}
4436
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
4437
+
response_data = aiomatic_parseMarkdown(response_data);
4438
+
}
4439
+
4440
+
var appendx = '<div class="ai-wrapper">';
4441
+
if (aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show') {
4442
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
4443
+
}
4444
+
appendx += '<div class="ai-bubble ai-other">' + response_data + '</div>';
4445
+
if (aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show') {
4446
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
4447
+
}
4448
+
appendx += '</div>';
4449
+
4450
+
if ((content_generated === '\n' || content_generated === ' \n' || content_generated === '.\n' || content_generated === '\n\n' || content_generated === '.\n\n' || content_generated === '"\n') && aiomatic_response_events > 0 && currentContent !== '') {
4451
+
if (!aiomatic_newline_before) {
4452
+
aiomatic_newline_before = true;
4453
+
jQuery('#aiomatic_chat_history' + instance).html(currentContent + '<br /><br />');
4454
+
}
4455
+
} else if (content_generated === '\n' && aiomatic_response_events === 0 && currentContent === '') {
4456
+
} else {
4457
+
aiomatic_newline_before = false;
4458
+
aiomatic_response_events += 1;
4459
+
jQuery('#aiomatic_chat_history' + instance).html(initialContent + appendx);
4460
+
}
4461
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
4462
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
4463
+
renderMathInElement(katexContainer, {
4464
+
delimiters: [
4465
+
4466
+
{ left: '\\(', right: '\\)', display: false },
4467
+
{ left: '\\[', right: '\\]', display: true }
4468
+
],
4469
+
throwOnError: false
4470
+
});
4471
+
}
4472
+
}
4473
+
if (hasFinishReason || count_line >= aiomatic_limitLines) {
4474
+
count_line += 1;
4475
+
aiomatic_response_events = 0;
4476
+
eventGenerator.close();
4477
+
jQuery('#aistopbut' + instance).hide();
4478
+
4479
+
var x_input_text = jQuery('#aiomatic_chat_history' + instance).html();
4480
+
if ((persistent != 'off' && persistent != '0' && persistent != '') && user_id != '0' && error_generated == '') {
4481
+
var save_persistent = x_input_text;
4482
+
if (persistent == 'vector') {
4483
+
save_persistent = user_question;
4484
+
}
4485
+
var saving_index = '';
4486
+
var main_index = '';
4487
+
if (persistent == 'history') {
4488
+
saving_index = jQuery('#chat-log-identifier' + instance).val();
4489
+
main_index = jQuery('#chat-main-identifier' + instance).val();
4490
+
}
4491
+
jQuery.ajax({
4492
+
type: 'POST',
4493
+
url: aiomatic_chat_ajax_object.ajax_url,
4494
+
data: {
4495
+
action: 'aiomatic_user_meta_save',
4496
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
4497
+
persistent: persistent,
4498
+
thread_id: aiomatic_chat_ajax_object.thread_id,
4499
+
x_input_text: save_persistent,
4500
+
user_id: user_id,
4501
+
saving_index: saving_index,
4502
+
main_index: main_index
4503
+
},
4504
+
success: function(result) {
4505
+
if (result.name && result.msg) {
4506
+
var logsdrop = jQuery('#chat-logs-dropdown' + instance);
4507
+
if (logsdrop) {
4508
+
var newChatLogItem = jQuery('<div class="chat-log-item" id="chat-log-item' + saving_index + '" data-id="' + saving_index + '" onclick="aiomatic_trigger_chat_logs(\'' + saving_index + '\', \'' + instance + '\')">' + result.name + '<span onclick="aiomatic_remove_chat_logs(event, \'' + saving_index + '\', \'' + instance + '\');" class="aiomatic-remove-item">X</span></div>');
4509
+
var chatLogNew = logsdrop.find('.chat-log-new');
4510
+
if (chatLogNew.length) {
4511
+
var nextSibling = chatLogNew.next();
4512
+
if (nextSibling.length && nextSibling.hasClass('date-group-label')) {
4513
+
newChatLogItem.insertAfter(nextSibling);
4514
+
} else {
4515
+
newChatLogItem.insertAfter(chatLogNew);
4516
+
}
4517
+
} else {
4518
+
logsdrop.append(newChatLogItem);
4519
+
}
4520
+
}
4521
+
}
4522
+
},
4523
+
error: function(error) {
4524
+
console.log('Error while saving persistent user log: ' + error.responseText);
4525
+
},
4526
+
});
4527
+
}
4528
+
4529
+
if (error_generated == '') {
4530
+
jQuery.ajax({
4531
+
type: 'POST',
4532
+
url: aiomatic_chat_ajax_object.ajax_url,
4533
+
data: {
4534
+
action: 'aiomatic_record_user_usage',
4535
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
4536
+
user_id: user_id,
4537
+
input_text: input_text,
4538
+
response_text: response_data,
4539
+
model: model,
4540
+
temp: temp,
4541
+
vision_file: vision_file,
4542
+
user_token_cap_per_day: aiomatic_chat_ajax_object.user_token_cap_per_day,
4543
+
source: 'chat'
4544
+
},
4545
+
success: function() {},
4546
+
error: function(error) {
4547
+
console.log('Error while saving user data: ' + error.responseText);
4548
+
},
4549
+
});
4550
+
}
4551
+
4552
+
if (error_generated == '') {
4553
+
jQuery('#openai-chat-response' + instance).html('??');
4554
+
}
4555
+
4556
+
var has_speech = false;
4557
+
if (aiomatic_chat_ajax_object.receive_message_sound != '') {
4558
+
var snd = new Audio(aiomatic_chat_ajax_object.receive_message_sound);
4559
+
snd.play();
4560
+
}
4561
+
4562
+
if (error_generated == '' && !jQuery('.aiomatic-gg-unmute').length) {
4563
+
if (aiomatic_chat_ajax_object.text_speech == 'elevenlabs') {
4564
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
4565
+
response_data = aiomatic_stripHtmlTags(response_data);
4566
+
if (response_data != '') {
4567
+
has_speech = true;
4568
+
let speechData = new FormData();
4569
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
4570
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
4571
+
speechData.append('x_input_text', response_data);
4572
+
speechData.append('action', 'aiomatic_get_elevenlabs_voice_chat');
4573
+
var speechRequest = new XMLHttpRequest();
4574
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
4575
+
speechRequest.responseType = "arraybuffer";
4576
+
speechRequest.ontimeout = () => {
4577
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
4578
+
jQuery('#openai-chat-response' + instance).html('??');
4579
+
aiomaticRmLoading(chatbut, instance);
4580
+
aiomatic_generator_working = false;
4581
+
};
4582
+
speechRequest.onerror = function() {
4583
+
console.error("Network Error");
4584
+
jQuery('#openai-chat-response' + instance).html('??');
4585
+
aiomaticRmLoading(chatbut, instance);
4586
+
aiomatic_generator_working = false;
4587
+
};
4588
+
speechRequest.onabort = function() {
4589
+
console.error("The request was aborted.");
4590
+
jQuery('#openai-chat-response' + instance).html('??');
4591
+
aiomaticRmLoading(chatbut, instance);
4592
+
aiomatic_generator_working = false;
4593
+
};
4594
+
speechRequest.onload = function() {
4595
+
var blob = new Blob([speechRequest.response], { type: "audio/mpeg" });
4596
+
var fr = new FileReader();
4597
+
fr.onload = function() {
4598
+
var fileText = this.result;
4599
+
try {
4600
+
var errorMessage = JSON.parse(fileText);
4601
+
console.log('ElevenLabs API failed: ' + errorMessage.msg);
4602
+
jQuery('#openai-chat-response' + instance).html('??');
4603
+
aiomaticRmLoading(chatbut, instance);
4604
+
aiomatic_generator_working = false;
4605
+
} catch (errorBlob) {
4606
+
var blobUrl = URL.createObjectURL(blob);
4607
+
var audioElement = document.createElement('audio');
4608
+
audioElement.src = blobUrl;
4609
+
audioElement.controls = true;
4610
+
audioElement.style.marginTop = "2px";
4611
+
audioElement.style.width = "100%";
4612
+
audioElement.id = 'audio-element-' + instance;
4613
+
audioElement.addEventListener("error", function(event) {
4614
+
console.error("Error loading or playing the audio: ", event);
4615
+
});
4616
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
4617
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
4618
+
if (aiomatic_chat_ajax_object.chat_waveform == 'on') {
4619
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div>');
4620
+
var waveform = WaveSurfer.create({
4621
+
container: '#waveform-container' + instance,
4622
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
4623
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
4624
+
backend: 'MediaElement',
4625
+
height: 60,
4626
+
barWidth: 2,
4627
+
responsive: true,
4628
+
mediaControls: false,
4629
+
interact: false
4630
+
});
4631
+
waveform.setMuted(true);
4632
+
waveform.load(blobUrl);
4633
+
waveform.on('ready', function() {
4634
+
waveform.play();
4635
+
});
4636
+
audioElement.addEventListener('play', function() {
4637
+
waveform.play();
4638
+
});
4639
+
audioElement.addEventListener('pause', function() {
4640
+
waveform.pause();
4641
+
});
4642
+
} else {
4643
+
jQuery('#openai-chat-response' + instance).html('??');
4644
+
}
4645
+
audioElement.play();
4646
+
aiomaticRmLoading(chatbut, instance);
4647
+
aiomatic_generator_working = false;
4648
+
}
4649
+
};
4650
+
fr.readAsText(blob);
4651
+
};
4652
+
speechRequest.send(speechData);
4653
+
}
4654
+
} else if (aiomatic_chat_ajax_object.text_speech == 'openai') {
4655
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
4656
+
response_data = aiomatic_stripHtmlTags(response_data);
4657
+
if (response_data != '') {
4658
+
has_speech = true;
4659
+
let speechData = new FormData();
4660
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
4661
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
4662
+
speechData.append('x_input_text', response_data);
4663
+
speechData.append('action', 'aiomatic_get_openai_voice_chat');
4664
+
var speechRequest = new XMLHttpRequest();
4665
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
4666
+
speechRequest.responseType = "arraybuffer";
4667
+
speechRequest.ontimeout = () => {
4668
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
4669
+
jQuery('#openai-chat-response' + instance).html('??');
4670
+
aiomaticRmLoading(chatbut, instance);
4671
+
aiomatic_generator_working = false;
4672
+
};
4673
+
speechRequest.onerror = function() {
4674
+
console.error("Network Error");
4675
+
jQuery('#openai-chat-response' + instance).html('??');
4676
+
aiomaticRmLoading(chatbut, instance);
4677
+
aiomatic_generator_working = false;
4678
+
};
4679
+
speechRequest.onabort = function() {
4680
+
console.error("The request was aborted.");
4681
+
jQuery('#openai-chat-response' + instance).html('??');
4682
+
aiomaticRmLoading(chatbut, instance);
4683
+
aiomatic_generator_working = false;
4684
+
};
4685
+
speechRequest.onload = function() {
4686
+
var blob = new Blob([speechRequest.response], { type: "audio/mpeg" });
4687
+
var fr = new FileReader();
4688
+
fr.onload = function() {
4689
+
var fileText = this.result;
4690
+
try {
4691
+
var errorMessage = JSON.parse(fileText);
4692
+
console.log('OpenAI TTS API failed: ' + errorMessage.msg);
4693
+
jQuery('#openai-chat-response' + instance).html('??');
4694
+
aiomaticRmLoading(chatbut, instance);
4695
+
aiomatic_generator_working = false;
4696
+
} catch (errorBlob) {
4697
+
var blobUrl = URL.createObjectURL(blob);
4698
+
var audioElement = document.createElement('audio');
4699
+
audioElement.src = blobUrl;
4700
+
audioElement.controls = true;
4701
+
audioElement.style.marginTop = "2px";
4702
+
audioElement.style.width = "100%";
4703
+
audioElement.id = 'audio-element-' + instance;
4704
+
audioElement.addEventListener("error", function(event) {
4705
+
console.error("Error loading or playing the audio: ", event);
4706
+
});
4707
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
4708
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
4709
+
if (aiomatic_chat_ajax_object.chat_waveform == 'on') {
4710
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div>');
4711
+
var waveform = WaveSurfer.create({
4712
+
container: '#waveform-container' + instance,
4713
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
4714
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
4715
+
backend: 'MediaElement',
4716
+
height: 60,
4717
+
barWidth: 2,
4718
+
responsive: true,
4719
+
mediaControls: false,
4720
+
interact: false
4721
+
});
4722
+
waveform.setMuted(true);
4723
+
waveform.load(blobUrl);
4724
+
waveform.on('ready', function() {
4725
+
waveform.play();
4726
+
});
4727
+
audioElement.addEventListener('play', function() {
4728
+
waveform.play();
4729
+
});
4730
+
audioElement.addEventListener('pause', function() {
4731
+
waveform.pause();
4732
+
});
4733
+
} else {
4734
+
jQuery('#openai-chat-response' + instance).html('??');
4735
+
}
4736
+
audioElement.play();
4737
+
aiomaticRmLoading(chatbut, instance);
4738
+
aiomatic_generator_working = false;
4739
+
}
4740
+
};
4741
+
fr.readAsText(blob);
4742
+
};
4743
+
speechRequest.send(speechData);
4744
+
}
4745
+
} else if (aiomatic_chat_ajax_object.text_speech == 'google') {
4746
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
4747
+
response_data = aiomatic_stripHtmlTags(response_data);
4748
+
if (response_data != '') {
4749
+
has_speech = true;
4750
+
let speechData = new FormData();
4751
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
4752
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
4753
+
speechData.append('x_input_text', response_data);
4754
+
speechData.append('action', 'aiomatic_get_google_voice_chat');
4755
+
var speechRequest = new XMLHttpRequest();
4756
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
4757
+
speechRequest.ontimeout = () => {
4758
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
4759
+
jQuery('#openai-chat-response' + instance).html('??');
4760
+
aiomaticRmLoading(chatbut, instance);
4761
+
aiomatic_generator_working = false;
4762
+
};
4763
+
speechRequest.onerror = function() {
4764
+
console.error("Network Error");
4765
+
jQuery('#openai-chat-response' + instance).html('??');
4766
+
aiomaticRmLoading(chatbut, instance);
4767
+
aiomatic_generator_working = false;
4768
+
};
4769
+
speechRequest.onabort = function() {
4770
+
console.error("The request was aborted.");
4771
+
jQuery('#openai-chat-response' + instance).html('??');
4772
+
aiomaticRmLoading(chatbut, instance);
4773
+
aiomatic_generator_working = false;
4774
+
};
4775
+
speechRequest.onload = function() {
4776
+
var result = speechRequest.responseText;
4777
+
try {
4778
+
var jsonresult = JSON.parse(result);
4779
+
if (jsonresult.status === 'success') {
4780
+
var byteCharacters = atob(jsonresult.audio);
4781
+
const byteNumbers = new Array(byteCharacters.length);
4782
+
for (let i = 0; i < byteCharacters.length; i++) {
4783
+
byteNumbers[i] = byteCharacters.charCodeAt(i);
4784
+
}
4785
+
const byteArray = new Uint8Array(byteNumbers);
4786
+
const blob = new Blob([byteArray], { type: 'audio/mp3' });
4787
+
var blobUrl = URL.createObjectURL(blob);
4788
+
var audioElement = document.createElement('audio');
4789
+
audioElement.src = blobUrl;
4790
+
audioElement.controls = true;
4791
+
audioElement.style.marginTop = "2px";
4792
+
audioElement.style.width = "100%";
4793
+
audioElement.id = 'audio-element-' + instance;
4794
+
audioElement.addEventListener("error", function(event) {
4795
+
console.error("Error loading or playing the audio: ", event);
4796
+
});
4797
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
4798
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
4799
+
if (aiomatic_chat_ajax_object.chat_waveform == 'on') {
4800
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div>');
4801
+
var waveform = WaveSurfer.create({
4802
+
container: '#waveform-container' + instance,
4803
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
4804
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
4805
+
backend: 'MediaElement',
4806
+
height: 60,
4807
+
barWidth: 2,
4808
+
responsive: true,
4809
+
mediaControls: false,
4810
+
interact: false
4811
+
});
4812
+
waveform.setMuted(true);
4813
+
waveform.load(blobUrl);
4814
+
waveform.on('ready', function() {
4815
+
waveform.play();
4816
+
});
4817
+
audioElement.addEventListener('play', function() {
4818
+
waveform.play();
4819
+
});
4820
+
audioElement.addEventListener('pause', function() {
4821
+
waveform.pause();
4822
+
});
4823
+
} else {
4824
+
jQuery('#openai-chat-response' + instance).html('??');
4825
+
}
4826
+
audioElement.play();
4827
+
aiomaticRmLoading(chatbut, instance);
4828
+
aiomatic_generator_working = false;
4829
+
} else {
4830
+
var errorMessageDetail = 'Google: ' + jsonresult.msg;
4831
+
console.log('Google Text-to-Speech error: ' + errorMessageDetail);
4832
+
jQuery('#openai-chat-response' + instance).html('??');
4833
+
aiomaticRmLoading(chatbut, instance);
4834
+
aiomatic_generator_working = false;
4835
+
}
4836
+
} catch (errorSpeech) {
4837
+
console.log('Exception in Google Text-to-Speech API: ' + errorSpeech);
4838
+
jQuery('#openai-chat-response' + instance).html('??');
4839
+
aiomaticRmLoading(chatbut, instance);
4840
+
aiomatic_generator_working = false;
4841
+
}
4842
+
};
4843
+
speechRequest.send(speechData);
4844
+
}
4845
+
} else if (aiomatic_chat_ajax_object.text_speech == 'did') {
4846
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
4847
+
response_data = aiomatic_stripHtmlTags(response_data);
4848
+
if (response_data != '') {
4849
+
has_speech = true;
4850
+
let speechData = new FormData();
4851
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
4852
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
4853
+
speechData.append('x_input_text', response_data);
4854
+
speechData.append('action', 'aiomatic_get_d_id_video_chat');
4855
+
var speechRequest = new XMLHttpRequest();
4856
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
4857
+
speechRequest.ontimeout = () => {
4858
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
4859
+
jQuery('#openai-chat-response' + instance).html('??');
4860
+
aiomaticRmLoading(chatbut, instance);
4861
+
aiomatic_generator_working = false;
4862
+
};
4863
+
speechRequest.onerror = function() {
4864
+
console.error("Network Error");
4865
+
jQuery('#openai-chat-response' + instance).html('??');
4866
+
aiomaticRmLoading(chatbut, instance);
4867
+
aiomatic_generator_working = false;
4868
+
};
4869
+
speechRequest.onabort = function() {
4870
+
console.error("The request was aborted.");
4871
+
jQuery('#openai-chat-response' + instance).html('??');
4872
+
aiomaticRmLoading(chatbut, instance);
4873
+
aiomatic_generator_working = false;
4874
+
};
4875
+
speechRequest.onload = function() {
4876
+
var result = speechRequest.responseText;
4877
+
try {
4878
+
var jsonresult = JSON.parse(result);
4879
+
if (jsonresult.status === 'success') {
4880
+
var videoURL = '<video class="ai_video" autoplay="autoplay" controls="controls"><source src="' + jsonresult.video + '" type="video/mp4"></video>';
4881
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-video">' + videoURL + '</div>');
4882
+
jQuery('#openai-chat-response' + instance).html('??');
4883
+
aiomaticRmLoading(chatbut, instance);
4884
+
aiomatic_generator_working = false;
4885
+
} else {
4886
+
var errorMessageDetail = 'D-ID: ' + jsonresult.msg;
4887
+
console.log('D-ID Text-to-video error: ' + errorMessageDetail);
4888
+
jQuery('#openai-chat-response' + instance).html('??');
4889
+
aiomaticRmLoading(chatbut, instance);
4890
+
aiomatic_generator_working = false;
4891
+
}
4892
+
} catch (errorSpeech) {
4893
+
console.log('Exception in D-ID Text-to-video API: ' + errorSpeech);
4894
+
jQuery('#openai-chat-response' + instance).html('??');
4895
+
aiomaticRmLoading(chatbut, instance);
4896
+
aiomatic_generator_working = false;
4897
+
}
4898
+
};
4899
+
speechRequest.send(speechData);
4900
+
}
4901
+
} else if (aiomatic_chat_ajax_object.text_speech == 'didstream') {
4902
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
4903
+
response_data = aiomatic_stripHtmlTags(response_data);
4904
+
if (response_data != '' && avatarImageUrl != '' && did_app_id != '' && streamingEpicFail === false) {
4905
+
has_speech = true;
4906
+
myStreamObject.talkToDidStream(response_data);
4907
+
jQuery('#openai-chat-response' + instance).html('??');
4908
+
aiomatic_generator_working = false;
4909
+
}
4910
+
} else if (aiomatic_chat_ajax_object.text_speech == 'azure') {
4911
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
4912
+
response_data = aiomatic_stripHtmlTags(response_data);
4913
+
if (response_data != '' && azure_speech_id != '' && streamingEpicFail === false) {
4914
+
has_speech = true;
4915
+
var ttsvoice = aiomatic_chat_ajax_object.azure_voice;
4916
+
var personalVoiceSpeakerProfileID = aiomatic_chat_ajax_object.azure_voice_profile;
4917
+
aiomaticRmLoading(chatbut, instance);
4918
+
azureSpeakText(response_data, ttsvoice, personalVoiceSpeakerProfileID);
4919
+
jQuery('#openai-chat-response' + instance).html('??');
4920
+
aiomatic_generator_working = false;
4921
+
}
4922
+
} else if (aiomatic_chat_ajax_object.text_speech == 'free') {
4923
+
var T2S;
4924
+
if ("speechSynthesis" in window || speechSynthesis) {
4925
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
4926
+
response_data = aiomatic_stripHtmlTags(response_data);
4927
+
if (response_data != '') {
4928
+
T2S = window.speechSynthesis || speechSynthesis;
4929
+
var utter = new SpeechSynthesisUtterance(response_data);
4930
+
var voiceSetting = aiomatic_chat_ajax_object.free_voice.split(";");
4931
+
var desiredVoiceName = voiceSetting[0].trim();
4932
+
var desiredLang = voiceSetting[1].trim();
4933
+
var voices = T2S.getVoices();
4934
+
var selectedVoice = voices.find(function(voice) {
4935
+
return voice.name === desiredVoiceName && voice.lang === desiredLang;
4936
+
});
4937
+
if (selectedVoice) {
4938
+
utter.voice = selectedVoice;
4939
+
utter.lang = selectedVoice.lang;
4940
+
} else {
4941
+
utter.lang = desiredLang;
4942
+
}
4943
+
T2S.speak(utter);
4944
+
}
4945
+
}
4946
+
}
4947
+
}
4948
+
4949
+
if (has_speech === false) {
4950
+
if (error_generated == '') {
4951
+
jQuery('#openai-chat-response' + instance).html('??');
4952
+
}
4953
+
aiomaticRmLoading(chatbut, instance);
4954
+
aiomatic_generator_working = false;
4955
+
}
4956
+
}
4957
+
}
4958
+
function handleContentBlockDelta(e)
4959
+
{
4960
+
if(aiomatic_chat_ajax_object.model_type == 'claude')
4961
+
{
4962
+
var aiomatic_newline_before = false;
4963
+
var aiomatic_response_events = 0;
4964
+
var aiomatic_limitLines = 1;
4965
+
var currentContent = jQuery('#aiomatic_chat_history' + instance).html();
4966
+
var resultData = null;
4967
+
if(e.data == '[DONE]')
4968
+
{
4969
+
var hasFinishReason = true;
4970
+
}
4971
+
else
4972
+
{
4973
+
try
4974
+
{
4975
+
resultData = JSON.parse(e.data);
4976
+
}
4977
+
catch (e)
4978
+
{
4979
+
console.warn(e);
4980
+
aiomaticRmLoading(chatbut, instance);
4981
+
aiomatic_generator_working = false;
4982
+
eventGenerator.close();
4983
+
jQuery('#aistopbut' + instance).hide();
4984
+
return;
4985
+
}
4986
+
var hasFinishReason = resultData &&
4987
+
(resultData.finish_reason === "stop" ||
4988
+
resultData.finish_reason === "length");
4989
+
if(resultData.stop_reason == 'stop_sequence' || resultData.stop_reason == 'max_tokens')
4990
+
{
4991
+
hasFinishReason = true;
4992
+
}
4993
+
}
4994
+
var content_generated = '';
4995
+
if(hasFinishReason){
4996
+
count_line += 1;
4997
+
aiomatic_response_events = 0;
4998
+
}
4999
+
else
5000
+
{
5001
+
if(resultData !== null)
5002
+
{
5003
+
var result = resultData;
5004
+
}
5005
+
else
5006
+
{
5007
+
var result = null;
5008
+
try {
5009
+
result = JSON.parse(e.data);
5010
+
}
5011
+
catch (e)
5012
+
{
5013
+
console.warn(e);
5014
+
aiomaticRmLoading(chatbut, instance);
5015
+
aiomatic_generator_working = false;
5016
+
jQuery('#aistopbut' + instance).hide();
5017
+
eventGenerator.close();
5018
+
return;
5019
+
};
5020
+
}
5021
+
if(result.error !== undefined){
5022
+
if(result.error !== undefined){
5023
+
error_generated = result.error[0].message;
5024
+
}
5025
+
else
5026
+
{
5027
+
error_generated = JSON.stringify(result.error);
5028
+
}
5029
+
if(error_generated === undefined)
5030
+
{
5031
+
error_generated = result.error.message;
5032
+
}
5033
+
if(error_generated === undefined)
5034
+
{
5035
+
error_generated = result.error;
5036
+
}
5037
+
console.log('Error while processing request(1a): ' + error_generated);
5038
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + error_generated + '</div>');
5039
+
}
5040
+
else
5041
+
{
5042
+
if(result.completion !== undefined)
5043
+
{
5044
+
content_generated = result.completion;
5045
+
}
5046
+
else if(result.delta.text !== undefined)
5047
+
{
5048
+
content_generated = result.delta.text;
5049
+
}
5050
+
else
5051
+
{
5052
+
console.log('Unrecognized format: ' + result);
5053
+
content_generated = '';
5054
+
}
5055
+
}
5056
+
if(aiomatic_chat_ajax_object.enable_html != true)
5057
+
{
5058
+
content_generated = aiomatic_esc_html(content_generated);
5059
+
}
5060
+
response_data += aiomatic_nl2br(content_generated);
5061
+
if(aiomatic_chat_ajax_object.strip_js == true)
5062
+
{
5063
+
response_data = response_data.replace(/<script[\s\S]*?<\/script>/gi, '');
5064
+
response_data = response_data.replace(/on\w+="[^"]*"/gi, '');
5065
+
}
5066
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
5067
+
response_data = processKatexMarkdown(response_data);
5068
+
}
5069
+
if(aiomatic_chat_ajax_object.markdown_parse == 'on')
5070
+
{
5071
+
response_data = aiomatic_parseMarkdown(response_data);
5072
+
}
5073
+
var appendx = '<div class="ai-wrapper">';
5074
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
5075
+
{
5076
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
5077
+
}
5078
+
appendx += '<div class="ai-bubble ai-other">' + response_data + '</div>';
5079
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
5080
+
{
5081
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
5082
+
}
5083
+
appendx += '</div>';
5084
+
if((content_generated === '\n' || content_generated === ' \n' || content_generated === '.\n' || content_generated === '\n\n' || content_generated === '.\n\n' || content_generated === '"\n') && aiomatic_response_events > 0 && currentContent !== ''){
5085
+
if(!aiomatic_newline_before) {
5086
+
aiomatic_newline_before = true;
5087
+
jQuery('#aiomatic_chat_history' + instance).html(currentContent + '<br /><br />');
5088
+
}
5089
+
}
5090
+
else if(content_generated === '\n' && aiomatic_response_events === 0 && currentContent === ''){
5091
+
}
5092
+
else
5093
+
{
5094
+
aiomatic_newline_before = false;
5095
+
aiomatic_response_events += 1;
5096
+
jQuery('#aiomatic_chat_history' + instance).html(initialContent + appendx);
5097
+
}
5098
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
5099
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
5100
+
renderMathInElement(katexContainer, {
5101
+
delimiters: [
5102
+
5103
+
{ left: '\\(', right: '\\)', display: false },
5104
+
{ left: '\\[', right: '\\]', display: true }
5105
+
],
5106
+
throwOnError: false
5107
+
});
5108
+
}
5109
+
}
5110
+
if(count_line >= aiomatic_limitLines)
5111
+
{
5112
+
eventGenerator.close();
5113
+
jQuery('#aistopbut' + instance).hide();
5114
+
var x_input_text = jQuery('#aiomatic_chat_history' + instance).html();
5115
+
if((persistent != 'off' && persistent != '0' && persistent != '') && user_id != '0' && error_generated == '')
5116
+
{
5117
+
var save_persistent = x_input_text;
5118
+
if(persistent == 'vector')
5119
+
{
5120
+
save_persistent = user_question;
5121
+
}
5122
+
var saving_index = '';
5123
+
var main_index = '';
5124
+
if(persistent == 'history')
5125
+
{
5126
+
saving_index = jQuery('#chat-log-identifier' + instance).val();
5127
+
main_index = jQuery('#chat-main-identifier' + instance).val();
5128
+
}
5129
+
jQuery.ajax({
5130
+
type: 'POST',
5131
+
url: aiomatic_chat_ajax_object.ajax_url,
5132
+
data: {
5133
+
action: 'aiomatic_user_meta_save',
5134
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
5135
+
persistent: persistent,
5136
+
thread_id: aiomatic_chat_ajax_object.thread_id,
5137
+
x_input_text: save_persistent,
5138
+
user_id: user_id,
5139
+
saving_index: saving_index,
5140
+
main_index: main_index
5141
+
},
5142
+
success: function(result) {
5143
+
if(result.name && result.msg)
5144
+
{
5145
+
var logsdrop = jQuery('#chat-logs-dropdown' + instance);
5146
+
if(logsdrop)
5147
+
{
5148
+
var newChatLogItem = jQuery('<div class="chat-log-item" id="chat-log-item' + saving_index + '" data-id="' + saving_index + '" onclick="aiomatic_trigger_chat_logs(\'' + saving_index + '\', \'' + instance + '\')">' + result.name + '<span onclick="aiomatic_remove_chat_logs(event, \'' + saving_index + '\', \'' + instance + '\');" class="aiomatic-remove-item">X</span></div>');
5149
+
var chatLogNew = logsdrop.find('.chat-log-new');
5150
+
if (chatLogNew.length)
5151
+
{
5152
+
var nextSibling = chatLogNew.next();
5153
+
if (nextSibling.length && nextSibling.hasClass('date-group-label'))
5154
+
{
5155
+
newChatLogItem.insertAfter(nextSibling);
5156
+
}
5157
+
else
5158
+
{
5159
+
newChatLogItem.insertAfter(chatLogNew);
5160
+
}
5161
+
}
5162
+
else
5163
+
{
5164
+
logsdrop.append(newChatLogItem);
5165
+
}
5166
+
}
5167
+
}
5168
+
},
5169
+
error: function(error) {
5170
+
console.log('Error while saving persistent user log: ' + error.responseText);
5171
+
},
5172
+
});
5173
+
}
5174
+
if(error_generated == '')
5175
+
{
5176
+
jQuery.ajax({
5177
+
type: 'POST',
5178
+
url: aiomatic_chat_ajax_object.ajax_url,
5179
+
data: {
5180
+
action: 'aiomatic_record_user_usage',
5181
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
5182
+
user_id: user_id,
5183
+
input_text: input_text,
5184
+
response_text: response_data,
5185
+
model: model,
5186
+
temp: temp,
5187
+
vision_file: vision_file,
5188
+
user_token_cap_per_day: aiomatic_chat_ajax_object.user_token_cap_per_day,
5189
+
source: 'chat'
5190
+
},
5191
+
success: function()
5192
+
{
5193
+
},
5194
+
error: function(error) {
5195
+
console.log('Error while saving user data: ' + error.responseText);
5196
+
},
5197
+
});
5198
+
}
5199
+
if(error_generated == '')
5200
+
{
5201
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5202
+
}
5203
+
var has_speech = false;
5204
+
if(aiomatic_chat_ajax_object.receive_message_sound != '')
5205
+
{
5206
+
var snd = new Audio(aiomatic_chat_ajax_object.receive_message_sound);
5207
+
snd.play();
5208
+
}
5209
+
if(error_generated == '' && !jQuery('.aiomatic-gg-unmute').length)
5210
+
{
5211
+
if(aiomatic_chat_ajax_object.text_speech == 'elevenlabs')
5212
+
{
5213
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
5214
+
response_data = aiomatic_stripHtmlTags(response_data);
5215
+
if(response_data != '')
5216
+
{
5217
+
has_speech = true;
5218
+
let speechData = new FormData();
5219
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
5220
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
5221
+
speechData.append('x_input_text', response_data);
5222
+
speechData.append('action', 'aiomatic_get_elevenlabs_voice_chat');
5223
+
var speechRequest = new XMLHttpRequest();
5224
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
5225
+
speechRequest.responseType = "arraybuffer";
5226
+
speechRequest.ontimeout = () => {
5227
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
5228
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5229
+
aiomaticRmLoading(chatbut, instance);
5230
+
aiomatic_generator_working = false;
5231
+
};
5232
+
speechRequest.onerror = function ()
5233
+
{
5234
+
console.error("Network Error");
5235
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5236
+
aiomaticRmLoading(chatbut, instance);
5237
+
aiomatic_generator_working = false;
5238
+
};
5239
+
speechRequest.onabort = function ()
5240
+
{
5241
+
console.error("The request was aborted.");
5242
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5243
+
aiomaticRmLoading(chatbut, instance);
5244
+
aiomatic_generator_working = false;
5245
+
};
5246
+
speechRequest.onload = function () {
5247
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
5248
+
var fr = new FileReader();
5249
+
fr.onload = function () {
5250
+
var fileText = this.result;
5251
+
try {
5252
+
var errorMessage = JSON.parse(fileText);
5253
+
console.log('ElevenLabs API failed: ' + errorMessage.msg);
5254
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5255
+
aiomaticRmLoading(chatbut, instance);
5256
+
aiomatic_generator_working = false;
5257
+
} catch (errorBlob) {
5258
+
var blobUrl = URL.createObjectURL(blob);
5259
+
var audioElement = document.createElement('audio');
5260
+
audioElement.src = blobUrl;
5261
+
audioElement.controls = true;
5262
+
audioElement.style.marginTop = "2px";
5263
+
audioElement.style.width = "100%";
5264
+
audioElement.id = 'audio-element-' + instance;
5265
+
audioElement.addEventListener("error", function(event) {
5266
+
console.error("Error loading or playing the audio: ", event);
5267
+
});
5268
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
5269
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
5270
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
5271
+
{
5272
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
5273
+
var waveform = WaveSurfer.create({
5274
+
container: '#waveform-container' + instance,
5275
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
5276
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
5277
+
backend: 'MediaElement',
5278
+
height: 60,
5279
+
barWidth: 2,
5280
+
responsive: true, mediaControls: false, interact: false
5281
+
});
5282
+
waveform.setMuted(true);
5283
+
waveform.load(blobUrl);
5284
+
waveform.on('ready', function () {
5285
+
waveform.play();
5286
+
});
5287
+
audioElement.addEventListener('play', function () {
5288
+
waveform.play();
5289
+
});
5290
+
audioElement.addEventListener('pause', function () {
5291
+
waveform.pause();
5292
+
});
5293
+
}
5294
+
else
5295
+
{
5296
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5297
+
}
5298
+
audioElement.play();
5299
+
aiomaticRmLoading(chatbut, instance);
5300
+
aiomatic_generator_working = false;
5301
+
}
5302
+
}
5303
+
fr.readAsText(blob);
5304
+
}
5305
+
speechRequest.send(speechData);
5306
+
}
5307
+
}
5308
+
else
5309
+
{
5310
+
if(aiomatic_chat_ajax_object.text_speech == 'openai')
5311
+
{
5312
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
5313
+
response_data = aiomatic_stripHtmlTags(response_data);
5314
+
if(response_data != '')
5315
+
{
5316
+
has_speech = true;
5317
+
let speechData = new FormData();
5318
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
5319
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
5320
+
speechData.append('x_input_text', response_data);
5321
+
speechData.append('action', 'aiomatic_get_openai_voice_chat');
5322
+
var speechRequest = new XMLHttpRequest();
5323
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
5324
+
speechRequest.responseType = "arraybuffer";
5325
+
speechRequest.ontimeout = () => {
5326
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
5327
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5328
+
aiomaticRmLoading(chatbut, instance);
5329
+
aiomatic_generator_working = false;
5330
+
};
5331
+
speechRequest.onerror = function ()
5332
+
{
5333
+
console.error("Network Error");
5334
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5335
+
aiomaticRmLoading(chatbut, instance);
5336
+
aiomatic_generator_working = false;
5337
+
};
5338
+
speechRequest.onabort = function ()
5339
+
{
5340
+
console.error("The request was aborted.");
5341
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5342
+
aiomaticRmLoading(chatbut, instance);
5343
+
aiomatic_generator_working = false;
5344
+
};
5345
+
speechRequest.onload = function () {
5346
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
5347
+
var fr = new FileReader();
5348
+
fr.onload = function () {
5349
+
var fileText = this.result;
5350
+
try {
5351
+
var errorMessage = JSON.parse(fileText);
5352
+
console.log('OpenAI TTS API failed: ' + errorMessage.msg);
5353
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5354
+
aiomaticRmLoading(chatbut, instance);
5355
+
aiomatic_generator_working = false;
5356
+
} catch (errorBlob) {
5357
+
var blobUrl = URL.createObjectURL(blob);
5358
+
var audioElement = document.createElement('audio');
5359
+
audioElement.src = blobUrl;
5360
+
audioElement.controls = true;
5361
+
audioElement.style.marginTop = "2px";
5362
+
audioElement.style.width = "100%";
5363
+
audioElement.id = 'audio-element-' + instance;
5364
+
audioElement.addEventListener("error", function(event) {
5365
+
console.error("Error loading or playing the audio: ", event);
5366
+
});
5367
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
5368
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
5369
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
5370
+
{
5371
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
5372
+
var waveform = WaveSurfer.create({
5373
+
container: '#waveform-container' + instance,
5374
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
5375
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
5376
+
backend: 'MediaElement',
5377
+
height: 60,
5378
+
barWidth: 2,
5379
+
responsive: true, mediaControls: false, interact: false
5380
+
});
5381
+
waveform.setMuted(true);
5382
+
waveform.load(blobUrl);
5383
+
waveform.on('ready', function () {
5384
+
waveform.play();
5385
+
});
5386
+
audioElement.addEventListener('play', function () {
5387
+
waveform.play();
5388
+
});
5389
+
audioElement.addEventListener('pause', function () {
5390
+
waveform.pause();
5391
+
});
5392
+
}
5393
+
else
5394
+
{
5395
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5396
+
}
5397
+
audioElement.play();
5398
+
aiomaticRmLoading(chatbut, instance);
5399
+
aiomatic_generator_working = false;
5400
+
}
5401
+
}
5402
+
fr.readAsText(blob);
5403
+
}
5404
+
speechRequest.send(speechData);
5405
+
}
5406
+
}
5407
+
else
5408
+
{
5409
+
if(aiomatic_chat_ajax_object.text_speech == 'google')
5410
+
{
5411
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
5412
+
response_data = aiomatic_stripHtmlTags(response_data);
5413
+
if(response_data != '')
5414
+
{
5415
+
has_speech = true;
5416
+
let speechData = new FormData();
5417
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
5418
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
5419
+
speechData.append('x_input_text', response_data);
5420
+
speechData.append('action', 'aiomatic_get_google_voice_chat');
5421
+
var speechRequest = new XMLHttpRequest();
5422
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
5423
+
speechRequest.ontimeout = () => {
5424
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
5425
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5426
+
aiomaticRmLoading(chatbut, instance);
5427
+
aiomatic_generator_working = false;
5428
+
};
5429
+
speechRequest.onerror = function ()
5430
+
{
5431
+
console.error("Network Error");
5432
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5433
+
aiomaticRmLoading(chatbut, instance);
5434
+
aiomatic_generator_working = false;
5435
+
};
5436
+
speechRequest.onabort = function ()
5437
+
{
5438
+
console.error("The request was aborted.");
5439
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5440
+
aiomaticRmLoading(chatbut, instance);
5441
+
aiomatic_generator_working = false;
5442
+
};
5443
+
speechRequest.onload = function () {
5444
+
var result = speechRequest.responseText;
5445
+
try {
5446
+
var jsonresult = JSON.parse(result);
5447
+
if(jsonresult.status === 'success'){
5448
+
var byteCharacters = atob(jsonresult.audio);
5449
+
const byteNumbers = new Array(byteCharacters.length);
5450
+
for (let i = 0; i < byteCharacters.length; i++) {
5451
+
byteNumbers[i] = byteCharacters.charCodeAt(i);
5452
+
}
5453
+
const byteArray = new Uint8Array(byteNumbers);
5454
+
const blob = new Blob([byteArray], {type: 'audio/mp3'});
5455
+
var blobUrl = URL.createObjectURL(blob);
5456
+
var audioElement = document.createElement('audio');
5457
+
audioElement.src = blobUrl;
5458
+
audioElement.controls = true;
5459
+
audioElement.style.marginTop = "2px";
5460
+
audioElement.style.width = "100%";
5461
+
audioElement.id = 'audio-element-' + instance;
5462
+
audioElement.addEventListener("error", function(event) {
5463
+
console.error("Error loading or playing the audio: ", event);
5464
+
});
5465
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
5466
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
5467
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
5468
+
{
5469
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
5470
+
var waveform = WaveSurfer.create({
5471
+
container: '#waveform-container' + instance,
5472
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
5473
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
5474
+
backend: 'MediaElement',
5475
+
height: 60,
5476
+
barWidth: 2,
5477
+
responsive: true, mediaControls: false, interact: false
5478
+
});
5479
+
waveform.setMuted(true);
5480
+
waveform.load(blobUrl);
5481
+
waveform.on('ready', function () {
5482
+
waveform.play();
5483
+
});
5484
+
audioElement.addEventListener('play', function () {
5485
+
waveform.play();
5486
+
});
5487
+
audioElement.addEventListener('pause', function () {
5488
+
waveform.pause();
5489
+
});
5490
+
}
5491
+
else
5492
+
{
5493
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5494
+
}
5495
+
audioElement.play();
5496
+
aiomaticRmLoading(chatbut, instance);
5497
+
aiomatic_generator_working = false;
5498
+
}
5499
+
else{
5500
+
var errorMessageDetail = 'Google: ' + jsonresult.msg;
5501
+
console.log('Google Text-to-Speech error: ' + errorMessageDetail);
5502
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5503
+
aiomaticRmLoading(chatbut, instance);
5504
+
aiomatic_generator_working = false;
5505
+
}
5506
+
}
5507
+
catch (errorSpeech){
5508
+
console.log('Exception in Google Text-to-Speech API: ' + errorSpeech);
5509
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5510
+
aiomaticRmLoading(chatbut, instance);
5511
+
aiomatic_generator_working = false;
5512
+
}
5513
+
}
5514
+
speechRequest.send(speechData);
5515
+
}
5516
+
}
5517
+
else
5518
+
{
5519
+
if(aiomatic_chat_ajax_object.text_speech == 'did')
5520
+
{
5521
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
5522
+
response_data = aiomatic_stripHtmlTags(response_data);
5523
+
if(response_data != '')
5524
+
{
5525
+
has_speech = true;
5526
+
let speechData = new FormData();
5527
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
5528
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
5529
+
speechData.append('x_input_text', response_data);
5530
+
speechData.append('action', 'aiomatic_get_d_id_video_chat');
5531
+
var speechRequest = new XMLHttpRequest();
5532
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
5533
+
speechRequest.ontimeout = () => {
5534
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
5535
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5536
+
aiomaticRmLoading(chatbut, instance);
5537
+
aiomatic_generator_working = false;
5538
+
};
5539
+
speechRequest.onerror = function ()
5540
+
{
5541
+
console.error("Network Error");
5542
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5543
+
aiomaticRmLoading(chatbut, instance);
5544
+
aiomatic_generator_working = false;
5545
+
};
5546
+
speechRequest.onabort = function ()
5547
+
{
5548
+
console.error("The request was aborted.");
5549
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5550
+
aiomaticRmLoading(chatbut, instance);
5551
+
aiomatic_generator_working = false;
5552
+
};
5553
+
speechRequest.onload = function () {
5554
+
var result = speechRequest.responseText;
5555
+
try
5556
+
{
5557
+
var jsonresult = JSON.parse(result);
5558
+
if(jsonresult.status === 'success')
5559
+
{
5560
+
var videoURL = '<video class="ai_video" autoplay="autoplay" controls="controls"><source src="' + jsonresult.video + '" type="video/mp4"></video>';
5561
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-video">' + videoURL + '</div>');
5562
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5563
+
aiomaticRmLoading(chatbut, instance);
5564
+
aiomatic_generator_working = false;
5565
+
}
5566
+
else
5567
+
{
5568
+
var errorMessageDetail = 'D-ID: ' + jsonresult.msg;
5569
+
console.log('D-ID Text-to-video error: ' + errorMessageDetail);
5570
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5571
+
aiomaticRmLoading(chatbut, instance);
5572
+
aiomatic_generator_working = false;
5573
+
}
5574
+
}
5575
+
catch (errorSpeech){
5576
+
console.log('Exception in D-ID Text-to-video API: ' + errorSpeech);
5577
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5578
+
aiomaticRmLoading(chatbut, instance);
5579
+
aiomatic_generator_working = false;
5580
+
}
5581
+
}
5582
+
speechRequest.send(speechData);
5583
+
}
5584
+
}
5585
+
else
5586
+
{
5587
+
if(aiomatic_chat_ajax_object.text_speech == 'didstream')
5588
+
{
5589
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
5590
+
response_data = aiomatic_stripHtmlTags(response_data);
5591
+
if(response_data != '')
5592
+
{
5593
+
if(avatarImageUrl != '' && did_app_id != '')
5594
+
{
5595
+
if(streamingEpicFail === false)
5596
+
{
5597
+
has_speech = true;
5598
+
myStreamObject.talkToDidStream(response_data);
5599
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5600
+
aiomatic_generator_working = false;
5601
+
}
5602
+
}
5603
+
}
5604
+
}
5605
+
else
5606
+
{
5607
+
if(aiomatic_chat_ajax_object.text_speech == 'azure')
5608
+
{
5609
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
5610
+
response_data = aiomatic_stripHtmlTags(response_data);
5611
+
if(response_data != '')
5612
+
{
5613
+
if(azure_speech_id != '')
5614
+
{
5615
+
if(streamingEpicFail === false)
5616
+
{
5617
+
has_speech = true;
5618
+
var ttsvoice = aiomatic_chat_ajax_object.azure_voice;
5619
+
var personalVoiceSpeakerProfileID = aiomatic_chat_ajax_object.azure_voice_profile;
5620
+
aiomaticRmLoading(chatbut, instance);
5621
+
azureSpeakText(response_data, ttsvoice, personalVoiceSpeakerProfileID);
5622
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5623
+
aiomatic_generator_working = false;
5624
+
}
5625
+
}
5626
+
}
5627
+
}
5628
+
else
5629
+
{
5630
+
if(aiomatic_chat_ajax_object.text_speech == 'free')
5631
+
{
5632
+
var T2S;
5633
+
if("speechSynthesis" in window || speechSynthesis)
5634
+
{
5635
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
5636
+
response_data = aiomatic_stripHtmlTags(response_data);
5637
+
if(response_data != '')
5638
+
{
5639
+
T2S = window.speechSynthesis || speechSynthesis;
5640
+
var utter = new SpeechSynthesisUtterance(response_data);
5641
+
var voiceSetting = aiomatic_chat_ajax_object.free_voice.split(";");
5642
+
var desiredVoiceName = voiceSetting[0].trim();
5643
+
var desiredLang = voiceSetting[1].trim();
5644
+
var voices = T2S.getVoices();
5645
+
var selectedVoice = voices.find(function(voice) {
5646
+
return voice.name === desiredVoiceName && voice.lang === desiredLang;
5647
+
});
5648
+
if (selectedVoice) {
5649
+
utter.voice = selectedVoice;
5650
+
utter.lang = selectedVoice.lang;
5651
+
}
5652
+
else
5653
+
{
5654
+
utter.lang = desiredLang;
5655
+
}
5656
+
T2S.speak(utter);
5657
+
}
5658
+
}
5659
+
}
5660
+
}
5661
+
}
5662
+
}
5663
+
}
5664
+
}
5665
+
}
5666
+
}
5667
+
if(has_speech === false)
5668
+
{
5669
+
if(error_generated == '')
5670
+
{
5671
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5672
+
}
5673
+
aiomaticRmLoading(chatbut, instance);
5674
+
aiomatic_generator_working = false;
5675
+
}
5676
+
}
5677
+
}
5678
+
}
5679
+
if(ai_assistant_id != '')
5680
+
{
5681
+
var run_id = '';
5682
+
var func_calls = 0;
5683
+
var response_data = '';
5684
+
var hasFinishReason = false;
5685
+
var content_generated = '';
5686
+
var th_id = '';
5687
+
eventGenerator.addEventListener('thread.created', threadCreatedEventHandler);
5688
+
eventGenerator.addEventListener('thread.run.created', threadRunCreatedEventHandler);
5689
+
eventGenerator.addEventListener('thread.run.queued', threadRunQueuedEventHandler);
5690
+
eventGenerator.addEventListener('thread.run.in_progress', threadRunInProgressEventHandler);
5691
+
eventGenerator.addEventListener('thread.run.requires_action', threadRunRequiresActionEventHandler);
5692
+
eventGenerator.addEventListener('thread.run.completed', threadRunCompletedEventHandler);
5693
+
eventGenerator.addEventListener('thread.run.failed', threadRunFailedEventHandler);
5694
+
eventGenerator.addEventListener('thread.run.cancelling', threadRunCancellingEventHandler);
5695
+
eventGenerator.addEventListener('thread.run.cancelled', threadRunCancelledEventHandler);
5696
+
eventGenerator.addEventListener('thread.run.expired', threadRunExpiredEventHandler);
5697
+
eventGenerator.addEventListener('thread.run.step.created', threadRunStepCreatedEventHandler);
5698
+
eventGenerator.addEventListener('thread.run.step.in_progress', threadRunStepInProgressEventHandler);
5699
+
eventGenerator.addEventListener('thread.run.step.delta', threadRunStepDeltaEventHandler);
5700
+
eventGenerator.addEventListener('thread.run.step.completed', threadRunStepCompletedEventHandler);
5701
+
eventGenerator.addEventListener('thread.run.step.failed', threadRunStepFailedEventHandler);
5702
+
eventGenerator.addEventListener('thread.run.step.cancelled', threadRunStepCancelledEventHandler);
5703
+
eventGenerator.addEventListener('thread.run.step.expired', threadRunStepExpiredEventHandler);
5704
+
eventGenerator.addEventListener('thread.message.created', threadMessageCreatedEventHandler);
5705
+
eventGenerator.addEventListener('thread.message.in_progress', threadMessageInProgressEventHandler);
5706
+
eventGenerator.addEventListener('thread.message.delta', threadMessageDeltaEventHandler);
5707
+
eventGenerator.addEventListener('thread.message.incomplete', threadMessageIncompleteEventHandler);
5708
+
eventGenerator.addEventListener('thread.message.completed', threadMessageCompletedEventHandler);
5709
+
eventGenerator.addEventListener('error', function(e) {
5710
+
var data = '';
5711
+
try
5712
+
{
5713
+
data = JSON.parse(e.data);
5714
+
}
5715
+
catch (errorSpeech){
5716
+
console.log('Exception streamerror: ' + errorSpeech);
5717
+
}
5718
+
console.error('Stream Error:', data);
5719
+
hasFinishReason = true;
5720
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5721
+
aiomaticRmLoading(chatbut, instance);
5722
+
aiomatic_generator_working = false;if (typeof eventGenerator !== 'undefined')
5723
+
{
5724
+
eventGenerator.close();
5725
+
jQuery('#aistopbut' + instance).hide();
5726
+
}
5727
+
});
5728
+
5729
+
eventGenerator.addEventListener('done', function(e) {
5730
+
console.log('Stream ended');
5731
+
hasFinishReason = true;
5732
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
5733
+
aiomaticRmLoading(chatbut, instance);
5734
+
aiomatic_generator_working = false;if (typeof eventGenerator !== 'undefined')
5735
+
{
5736
+
eventGenerator.close();
5737
+
jQuery('#aistopbut' + instance).hide();
5738
+
}
5739
+
});
5740
+
if(aiomatic_chat_ajax_object.is_azure == '1')
5741
+
{
5742
+
eventGenerator.onmessage = handleMessageEvent;
5743
+
}
5744
+
}
5745
+
else
5746
+
{
5747
+
eventGenerator.onmessage = handleMessageEvent;
5748
+
eventGenerator.addEventListener('content_block_delta', handleContentBlockDelta);
5749
+
eventGenerator.addEventListener('message_stop', handleMessageStopEvent);
5750
+
eventGenerator.addEventListener('completion', handleCompletionEvent);
5751
+
5752
+
eventGenerator.addEventListener('response.output_text.delta', handleContentBlockDeltaResponses);
5753
+
eventGenerator.addEventListener('response.completed', handleResponsesMessageStopEvent);
5754
+
eventGenerator.addEventListener('response.failed', handleResponsesMessageFailedEvent);
5755
+
eventGenerator.addEventListener('response.incomplete', function (event) {
5756
+
console.log('Incomplete message');
5757
+
});
5758
+
eventGenerator.addEventListener('error', handleMessageErrorEvent);
5759
+
5760
+
//eventGenerator.addEventListener('response.created', e => console.log('Response created'));
5761
+
//eventGenerator.addEventListener('response.in_progress', e => console.log('Response in progress'));
5762
+
5763
+
eventGenerator.addEventListener('response.output_item.added', handleOutputItemAdded);
5764
+
//eventGenerator.addEventListener('response.output_item.done', e => console.log('Output item done'));
5765
+
5766
+
//eventGenerator.addEventListener('response.content_part.added', e => console.log('Content part added'));
5767
+
//eventGenerator.addEventListener('response.content_part.done', e => console.log('Content part done'));
5768
+
5769
+
//eventGenerator.addEventListener('response.output_text.done', e => console.log('Output text done'));
5770
+
5771
+
//eventGenerator.addEventListener('response.output_text.annotation.added', e => console.log('Annotation added'));
5772
+
5773
+
//eventGenerator.addEventListener('response.refusal.delta', e => console.log('Refusal delta'));
5774
+
5775
+
//eventGenerator.addEventListener('response.reasoning_summary_part.added', e => console.log('Reasoning summary part added'));
5776
+
//eventGenerator.addEventListener('response.reasoning_summary_part.done', e => console.log('Reasoning summary part done'));
5777
+
5778
+
//eventGenerator.addEventListener('response.reasoning_summary_text.delta', e => console.log('Reasoning summary delta'));
5779
+
//eventGenerator.addEventListener('response.reasoning_summary_text.done', e => console.log('Reasoning summary done'));
5780
+
eventGenerator.addEventListener('response.refusal.done', handleRefusalDone);
5781
+
5782
+
eventGenerator.addEventListener('response.function_call_arguments.delta', handleFunctionCallArgumentsDelta);
5783
+
eventGenerator.addEventListener('response.function_call_arguments.done', handleFunctionCallArgumentsDone);
5784
+
5785
+
eventGenerator.addEventListener('response.file_search_call.in_progress', e => console.log('File search in progress'));
5786
+
eventGenerator.addEventListener('response.file_search_call.searching', e => console.log('File search searching'));
5787
+
eventGenerator.addEventListener('response.file_search_call.completed', e => console.log('File search completed'));
5788
+
5789
+
eventGenerator.addEventListener('response.web_search_call.in_progress', e => console.log('Web search in progress'));
5790
+
eventGenerator.addEventListener('response.web_search_call.searching', e => console.log('Web search searching'));
5791
+
eventGenerator.addEventListener('response.web_search_call.completed', e => console.log('Web search completed'));
5792
+
5793
+
}
5794
+
function handleFunctionCallArgumentsDelta(e)
5795
+
{
5796
+
try
5797
+
{
5798
+
const deltaString = e.data;
5799
+
if (deltaString) {
5800
+
const parsed = JSON.parse(deltaString);
5801
+
if(parsed.delta)
5802
+
{
5803
+
func_call_var += parsed.delta;
5804
+
}
5805
+
}
5806
+
} catch (err) {
5807
+
console.warn('Unable to parse responses delta chunk:', e.delta, err);
5808
+
}
5809
+
}
5810
+
function handleOutputItemAdded(e) {
5811
+
try {
5812
+
const data = JSON.parse(e.data);
5813
+
5814
+
if (data?.item?.type === 'function_call' && data.item.name) {
5815
+
function_call_name = data.item.name;
5816
+
//console.log('Function name detected:', function_call_name);
5817
+
}
5818
+
if (data?.item?.type === 'function_call' && data.item.id) {
5819
+
function_call_id = data.item.id;
5820
+
}
5821
+
} catch (err) {
5822
+
console.warn('Error parsing output_item.added:', err);
5823
+
}
5824
+
}
5825
+
function handleFunctionCallArgumentsDone(e) {
5826
+
//console.log('Function call fully received:', JSON.stringify(e.data));
5827
+
5828
+
jQuery.ajax({
5829
+
type: 'POST',
5830
+
async: false,
5831
+
url: aiomatic_chat_ajax_object.ajax_url,
5832
+
data: {
5833
+
action: 'aiomatic_call_ai_function_responses',
5834
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
5835
+
func_call: func_call_var,
5836
+
function_name: function_call_name,
5837
+
function_call_id: function_call_id,
5838
+
},
5839
+
success: function(result) {
5840
+
if (typeof result !== "object" || result === null)
5841
+
{
5842
+
try
5843
+
{
5844
+
result = JSON.parse(result);
5845
+
}
5846
+
catch (error) {}
5847
+
}
5848
+
if(result.scope == 'fail')
5849
+
{
5850
+
console.log('Error while calling parsing functions: ' + JSON.stringify(result));
5851
+
hasFinishReason = true;
5852
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
5853
+
aiomaticRmLoading(chatbut, instance);
5854
+
aiomatic_generator_working = false;
5855
+
if (typeof eventGenerator !== 'undefined')
5856
+
{
5857
+
eventGenerator.close();
5858
+
jQuery('#aistopbut' + instance).hide();
5859
+
}
5860
+
return;
5861
+
}
5862
+
else
5863
+
{
5864
+
if(result.scope == 'response')
5865
+
{
5866
+
console.log('Recalling AI stream chat');
5867
+
if (typeof eventGenerator !== 'undefined')
5868
+
{
5869
+
eventGenerator.close();
5870
+
jQuery('#aistopbut' + instance).hide();
5871
+
}
5872
+
if(aiomatic_chat_ajax_object.enable_god_mode == '')
5873
+
{
5874
+
aiomatic_chat_ajax_object.enable_god_mode = 'off';
5875
+
}
5876
+
var internet_permission = aiomatic_chat_ajax_object.internet_access;
5877
+
if(jQuery('#aiomatic-globe-overlay' + instance).hasClass('aiomatic-globe-bar') && jQuery('#aiomatic-globe-overlay' + instance).is(':visible'))
5878
+
{
5879
+
internet_permission = 'disabled';
5880
+
}
5881
+
eventURL = aiomatic_chat_ajax_object.stream_url;
5882
+
if(pdf_data != '')
5883
+
{
5884
+
eventURL += '&pdf_data=' + encodeURIComponent(pdf_data);
5885
+
}
5886
+
if(file_data != '')
5887
+
{
5888
+
eventURL += '&file_data=' + encodeURIComponent(file_data);
5889
+
}
5890
+
if(aiomatic_chat_ajax_object.user_token_cap_per_day != '')
5891
+
{
5892
+
eventURL += '&user_token_cap_per_day=' + encodeURIComponent(aiomatic_chat_ajax_object.user_token_cap_per_day);
5893
+
}
5894
+
if(aiomatic_chat_ajax_object.user_id != '')
5895
+
{
5896
+
eventURL += '&user_id=' + encodeURIComponent(aiomatic_chat_ajax_object.user_id);
5897
+
}
5898
+
if(aiomatic_chat_ajax_object.frequency != '')
5899
+
{
5900
+
eventURL += '&frequency=' + encodeURIComponent(aiomatic_chat_ajax_object.frequency);
5901
+
}
5902
+
if(aiomatic_chat_ajax_object.store_data != '')
5903
+
{
5904
+
eventURL += '&store_data=' + encodeURIComponent(aiomatic_chat_ajax_object.store_data);
5905
+
}
5906
+
if(aiomatic_chat_ajax_object.presence != '')
5907
+
{
5908
+
eventURL += '&presence=' + encodeURIComponent(aiomatic_chat_ajax_object.presence);
5909
+
}
5910
+
if(aiomatic_chat_ajax_object.top_p != '')
5911
+
{
5912
+
eventURL += '&top_p=' + encodeURIComponent(aiomatic_chat_ajax_object.top_p);
5913
+
}
5914
+
if(aiomatic_chat_ajax_object.temp != '')
5915
+
{
5916
+
eventURL += '&temp=' + encodeURIComponent(aiomatic_chat_ajax_object.temp);
5917
+
}
5918
+
if(aiomatic_chat_ajax_object.model != '')
5919
+
{
5920
+
eventURL += '&model=' + encodeURIComponent(aiomatic_chat_ajax_object.model);
5921
+
}
5922
+
if(ai_assistant_id != '')
5923
+
{
5924
+
eventURL += '&assistant_id=' + encodeURIComponent(ai_assistant_id);
5925
+
}
5926
+
if(th_id != '')
5927
+
{
5928
+
eventURL += '&thread_id=' + encodeURIComponent(th_id);
5929
+
}
5930
+
if(remember_string != '')
5931
+
{
5932
+
eventURL += '&remember_string=' + encodeURIComponent(remember_string);
5933
+
}
5934
+
if(is_modern_gpt != '')
5935
+
{
5936
+
eventURL += '&is_modern_gpt=' + encodeURIComponent(is_modern_gpt);
5937
+
}
5938
+
if(internet_permission != '')
5939
+
{
5940
+
eventURL += '&internet_access=' + encodeURIComponent(internet_permission);
5941
+
}
5942
+
if(aiomatic_chat_ajax_object.embeddings != '')
5943
+
{
5944
+
eventURL += '&embeddings=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings);
5945
+
}
5946
+
if(aiomatic_chat_ajax_object.embeddings_namespace != '')
5947
+
{
5948
+
eventURL += '&embeddings_namespace=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings_namespace);
5949
+
}
5950
+
if(user_question != '')
5951
+
{
5952
+
eventURL += '&user_question=' + encodeURIComponent(user_question);
5953
+
}
5954
+
if(enable_god_mode != '')
5955
+
{
5956
+
eventURL += '&enable_god_mode=' + encodeURIComponent(enable_god_mode);
5957
+
}
5958
+
if(mcp_servers != '')
5959
+
{
5960
+
eventURL += '&mcp_servers=' + encodeURIComponent(mcp_servers);
5961
+
}
5962
+
if(aiomatic_chat_ajax_object.bots_data && aiomatic_chat_ajax_object.strip_botname == '1')
5963
+
{
5964
+
aiomatic_chat_ajax_object.bots_data.forEach((relement) => input_text = input_text.replace('@' + relement.name, ''));
5965
+
}
5966
+
eventURL += '&input_text=' + encodeURIComponent(input_text);
5967
+
if(vision_file != '')
5968
+
{
5969
+
eventURL += '&vision_file=' + encodeURIComponent(vision_file);
5970
+
}
5971
+
var fnrez = JSON.stringify(result.data);
5972
+
eventURL += '&functions_result=' + encodeURIComponent(fnrez);
5973
+
if(run_id != '')
5974
+
{
5975
+
eventURL += '&run_id=' + encodeURIComponent(run_id);
5976
+
}
5977
+
if(eventURL.length > 2080)
5978
+
{
5979
+
console.log('URL too long, using alternative processing method');
5980
+
var unid = "id" + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
5981
+
aiChatUploadDataomatic(aiomatic_chat_ajax_object, unid, input_text, remember_string, user_question, fnrez);
5982
+
eventURL = aiomatic_chat_ajax_object.stream_url;
5983
+
eventURL += '&input_text=0&remember_string=0&user_question=0&functions_result=0';
5984
+
if(pdf_data != '')
5985
+
{
5986
+
eventURL += '&pdf_data=' + encodeURIComponent(pdf_data);
5987
+
}
5988
+
if(file_data != '')
5989
+
{
5990
+
eventURL += '&file_data=' + encodeURIComponent(file_data);
5991
+
}
5992
+
if(aiomatic_chat_ajax_object.user_token_cap_per_day != '')
5993
+
{
5994
+
eventURL += '&user_token_cap_per_day=' + encodeURIComponent(aiomatic_chat_ajax_object.user_token_cap_per_day);
5995
+
}
5996
+
if(aiomatic_chat_ajax_object.user_id != '')
5997
+
{
5998
+
eventURL += '&user_id=' + encodeURIComponent(aiomatic_chat_ajax_object.user_id);
5999
+
}
6000
+
if(aiomatic_chat_ajax_object.frequency != '')
6001
+
{
6002
+
eventURL += '&frequency=' + encodeURIComponent(aiomatic_chat_ajax_object.frequency);
6003
+
}
6004
+
if(aiomatic_chat_ajax_object.store_data != '')
6005
+
{
6006
+
eventURL += '&store_data=' + encodeURIComponent(aiomatic_chat_ajax_object.store_data);
6007
+
}
6008
+
if(aiomatic_chat_ajax_object.presence != '')
6009
+
{
6010
+
eventURL += '&presence=' + encodeURIComponent(aiomatic_chat_ajax_object.presence);
6011
+
}
6012
+
if(aiomatic_chat_ajax_object.top_p != '')
6013
+
{
6014
+
eventURL += '&top_p=' + encodeURIComponent(aiomatic_chat_ajax_object.top_p);
6015
+
}
6016
+
if(aiomatic_chat_ajax_object.temp != '')
6017
+
{
6018
+
eventURL += '&temp=' + encodeURIComponent(aiomatic_chat_ajax_object.temp);
6019
+
}
6020
+
if(aiomatic_chat_ajax_object.model != '')
6021
+
{
6022
+
eventURL += '&model=' + encodeURIComponent(aiomatic_chat_ajax_object.model);
6023
+
}
6024
+
if(ai_assistant_id != '')
6025
+
{
6026
+
eventURL += '&assistant_id=' + encodeURIComponent(ai_assistant_id);
6027
+
}
6028
+
if(th_id != '')
6029
+
{
6030
+
eventURL += '&thread_id=' + encodeURIComponent(th_id);
6031
+
}
6032
+
if(is_modern_gpt != '')
6033
+
{
6034
+
eventURL += '&is_modern_gpt=' + encodeURIComponent(is_modern_gpt);
6035
+
}
6036
+
if(internet_permission != '')
6037
+
{
6038
+
eventURL += '&internet_access=' + encodeURIComponent(internet_permission);
6039
+
}
6040
+
if(aiomatic_chat_ajax_object.embeddings != '')
6041
+
{
6042
+
eventURL += '&embeddings=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings);
6043
+
}
6044
+
if(aiomatic_chat_ajax_object.embeddings_namespace != '')
6045
+
{
6046
+
eventURL += '&embeddings_namespace=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings_namespace);
6047
+
}
6048
+
if(enable_god_mode != '')
6049
+
{
6050
+
eventURL += '&enable_god_mode=' + encodeURIComponent(enable_god_mode);
6051
+
}
6052
+
if(mcp_servers != '')
6053
+
{
6054
+
eventURL += '&mcp_servers=' + encodeURIComponent(mcp_servers);
6055
+
}
6056
+
if(vision_file != '')
6057
+
{
6058
+
eventURL += '&vision_file=' + encodeURIComponent(vision_file);
6059
+
}
6060
+
if(run_id != '')
6061
+
{
6062
+
eventURL += '&run_id=' + encodeURIComponent(run_id);
6063
+
}
6064
+
eventURL += '&bufferid=' + encodeURIComponent(unid);
6065
+
}
6066
+
func_call = {
6067
+
init_data: {
6068
+
pdf_data: pdf_data,
6069
+
file_data: file_data,
6070
+
user_token_cap_per_day: aiomatic_chat_ajax_object.user_token_cap_per_day,
6071
+
user_id: aiomatic_chat_ajax_object.user_id,
6072
+
store_data: aiomatic_chat_ajax_object.store_data,
6073
+
frequency: aiomatic_chat_ajax_object.frequency,
6074
+
presence: aiomatic_chat_ajax_object.presence,
6075
+
top_p: aiomatic_chat_ajax_object.top_p,
6076
+
temp: aiomatic_chat_ajax_object.temp,
6077
+
model: aiomatic_chat_ajax_object.model,
6078
+
input_text: input_text,
6079
+
remember_string: remember_string,
6080
+
is_modern_gpt: is_modern_gpt,
6081
+
user_question: user_question
6082
+
},
6083
+
};
6084
+
try
6085
+
{
6086
+
eventGenerator = new EventSource(eventURL);
6087
+
}
6088
+
catch(e)
6089
+
{
6090
+
console.log('Error in Event startup: ' + e);
6091
+
}
6092
+
eventGenerator.onerror = handleErrorEvent1;
6093
+
hasFinishReason = false;
6094
+
if(ai_assistant_id != '')
6095
+
{
6096
+
eventGenerator.addEventListener('thread.created', threadCreatedEventHandler);
6097
+
eventGenerator.addEventListener('thread.run.created', threadRunCreatedEventHandler);
6098
+
eventGenerator.addEventListener('thread.run.queued', threadRunQueuedEventHandler);
6099
+
eventGenerator.addEventListener('thread.run.in_progress', threadRunInProgressEventHandler);
6100
+
eventGenerator.addEventListener('thread.run.requires_action', threadRunRequiresActionEventHandler);
6101
+
eventGenerator.addEventListener('thread.run.completed', threadRunCompletedEventHandler);
6102
+
eventGenerator.addEventListener('thread.run.failed', threadRunFailedEventHandler);
6103
+
eventGenerator.addEventListener('thread.run.cancelling', threadRunCancellingEventHandler);
6104
+
eventGenerator.addEventListener('thread.run.cancelled', threadRunCancelledEventHandler);
6105
+
eventGenerator.addEventListener('thread.run.expired', threadRunExpiredEventHandler);
6106
+
eventGenerator.addEventListener('thread.run.step.created', threadRunStepCreatedEventHandler);
6107
+
eventGenerator.addEventListener('thread.run.step.in_progress', threadRunStepInProgressEventHandler);
6108
+
eventGenerator.addEventListener('thread.run.step.delta', threadRunStepDeltaEventHandler);
6109
+
eventGenerator.addEventListener('thread.run.step.completed', threadRunStepCompletedEventHandler);
6110
+
eventGenerator.addEventListener('thread.run.step.failed', threadRunStepFailedEventHandler);
6111
+
eventGenerator.addEventListener('thread.run.step.cancelled', threadRunStepCancelledEventHandler);
6112
+
eventGenerator.addEventListener('thread.run.step.expired', threadRunStepExpiredEventHandler);
6113
+
eventGenerator.addEventListener('thread.message.created', threadMessageCreatedEventHandler);
6114
+
eventGenerator.addEventListener('thread.message.in_progress', threadMessageInProgressEventHandler);
6115
+
eventGenerator.addEventListener('thread.message.delta', threadMessageDeltaEventHandler);
6116
+
eventGenerator.addEventListener('thread.message.incomplete', threadMessageIncompleteEventHandler);
6117
+
eventGenerator.addEventListener('thread.message.completed', threadMessageCompletedEventHandler);
6118
+
}
6119
+
else
6120
+
{
6121
+
eventGenerator.onmessage = handleMessageEvent;
6122
+
eventGenerator.addEventListener('content_block_delta', handleContentBlockDelta);
6123
+
eventGenerator.addEventListener('message_stop', handleMessageStopEvent);
6124
+
eventGenerator.addEventListener('completion', handleCompletionEvent);
6125
+
6126
+
eventGenerator.addEventListener('response.output_text.delta', handleContentBlockDeltaResponses);
6127
+
eventGenerator.addEventListener('response.completed', handleResponsesMessageStopEvent);
6128
+
eventGenerator.addEventListener('response.failed', handleResponsesMessageFailedEvent);
6129
+
eventGenerator.addEventListener('response.incomplete', function (event) {
6130
+
console.log('Incomplete message');
6131
+
});
6132
+
eventGenerator.addEventListener('error', handleMessageErrorEvent);
6133
+
6134
+
//eventGenerator.addEventListener('response.created', e => console.log('Response created'));
6135
+
//eventGenerator.addEventListener('response.in_progress', e => console.log('Response in progress'));
6136
+
6137
+
eventGenerator.addEventListener('response.output_item.added', handleOutputItemAdded);
6138
+
//eventGenerator.addEventListener('response.output_item.done', e => console.log('Output item done'));
6139
+
6140
+
//eventGenerator.addEventListener('response.content_part.added', e => console.log('Content part added'));
6141
+
//eventGenerator.addEventListener('response.content_part.done', e => console.log('Content part done'));
6142
+
6143
+
//eventGenerator.addEventListener('response.output_text.done', e => console.log('Output text done'));
6144
+
6145
+
//eventGenerator.addEventListener('response.output_text.annotation.added', e => console.log('Annotation added'));
6146
+
6147
+
//eventGenerator.addEventListener('response.refusal.delta', e => console.log('Refusal delta'));
6148
+
6149
+
//eventGenerator.addEventListener('response.reasoning_summary_part.added', e => console.log('Reasoning summary part added'));
6150
+
//eventGenerator.addEventListener('response.reasoning_summary_part.done', e => console.log('Reasoning summary part done'));
6151
+
6152
+
//eventGenerator.addEventListener('response.reasoning_summary_text.delta', e => console.log('Reasoning summary delta'));
6153
+
//eventGenerator.addEventListener('response.reasoning_summary_text.done', e => console.log('Reasoning summary done'));
6154
+
eventGenerator.addEventListener('response.refusal.done', handleRefusalDone);
6155
+
6156
+
eventGenerator.addEventListener('response.function_call_arguments.delta', handleFunctionCallArgumentsDelta);
6157
+
eventGenerator.addEventListener('response.function_call_arguments.done', handleFunctionCallArgumentsDone);
6158
+
6159
+
eventGenerator.addEventListener('response.file_search_call.in_progress', e => console.log('File search in progress'));
6160
+
eventGenerator.addEventListener('response.file_search_call.searching', e => console.log('File search searching'));
6161
+
eventGenerator.addEventListener('response.file_search_call.completed', e => console.log('File search completed'));
6162
+
6163
+
eventGenerator.addEventListener('response.web_search_call.in_progress', e => console.log('Web search in progress'));
6164
+
eventGenerator.addEventListener('response.web_search_call.searching', e => console.log('Web search searching'));
6165
+
eventGenerator.addEventListener('response.web_search_call.completed', e => console.log('Web search completed'));
6166
+
}
6167
+
eventGenerator.addEventListener('error', function(e) {
6168
+
if (typeof result !== "object" || result === null)
6169
+
{
6170
+
try
6171
+
{
6172
+
var data = JSON.parse(e.data);
6173
+
console.error('Stream Error:', data);
6174
+
}
6175
+
catch (error) {
6176
+
console.error('Stream parse Error:', error);
6177
+
}
6178
+
}
6179
+
hasFinishReason = true;
6180
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6181
+
aiomaticRmLoading(chatbut, instance);
6182
+
aiomatic_generator_working = false;if (typeof eventGenerator !== 'undefined')
6183
+
{
6184
+
eventGenerator.close();
6185
+
jQuery('#aistopbut' + instance).hide();
6186
+
}
6187
+
});
6188
+
6189
+
eventGenerator.addEventListener('done', function(e) {
6190
+
console.log('Stream ended');
6191
+
hasFinishReason = true;
6192
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6193
+
aiomaticRmLoading(chatbut, instance);
6194
+
aiomatic_generator_working = false;if (typeof eventGenerator !== 'undefined')
6195
+
{
6196
+
eventGenerator.close();
6197
+
jQuery('#aistopbut' + instance).hide();
6198
+
}
6199
+
});
6200
+
}
6201
+
else
6202
+
{
6203
+
var appendx = '<div class="ai-wrapper">';
6204
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
6205
+
{
6206
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
6207
+
}
6208
+
appendx += '<div class="ai-bubble ai-other">' + result.data + '</div>';
6209
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
6210
+
{
6211
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
6212
+
}
6213
+
appendx += '</div>';
6214
+
if(result.scope == 'end_message')
6215
+
{
6216
+
const inputField = document.getElementById('aiomatic_chat_input' + instance);
6217
+
inputField.disabled = true;
6218
+
inputField.chatended = true;
6219
+
const speechButton = document.getElementById('openai-chat-speech-button' + instance);
6220
+
if (speechButton) {
6221
+
speechButton.disabled = true;
6222
+
}
6223
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.conversation_ended + '</div>');
6224
+
aiomaticRmLoading(chatbut, instance);
6225
+
return;
6226
+
}
6227
+
if(result.scope == 'user_message')
6228
+
{
6229
+
hasFinishReason = true;
6230
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
6231
+
appendx = processKatexMarkdown(appendx);
6232
+
}
6233
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
6234
+
appendx = aiomatic_parseMarkdown(appendx);
6235
+
}
6236
+
jQuery('#aiomatic_chat_history' + instance).html(initialContent + appendx);
6237
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
6238
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
6239
+
renderMathInElement(katexContainer, {
6240
+
delimiters: [
6241
+
6242
+
{ left: '\\(', right: '\\)', display: false },
6243
+
{ left: '\\[', right: '\\]', display: true }
6244
+
],
6245
+
throwOnError: false
6246
+
});
6247
+
}
6248
+
if (typeof eventGenerator !== 'undefined')
6249
+
{
6250
+
eventGenerator.close();
6251
+
jQuery('#aistopbut' + instance).hide();
6252
+
}
6253
+
aiomaticRmLoading(chatbut, instance);
6254
+
aiomatic_generator_working = false;
6255
+
}
6256
+
else
6257
+
{
6258
+
console.log('Unknown scope returned: ' + result);
6259
+
hasFinishReason = true;
6260
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
6261
+
aiomaticRmLoading(chatbut, instance);
6262
+
aiomatic_generator_working = false;
6263
+
if (typeof eventGenerator !== 'undefined')
6264
+
{
6265
+
eventGenerator.close();
6266
+
jQuery('#aistopbut' + instance).hide();
6267
+
}
6268
+
return;
6269
+
}
6270
+
}
6271
+
}
6272
+
},
6273
+
error: function(err) {
6274
+
console.error('Function call AJAX failed:', err.responseText);
6275
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
6276
+
aiomaticRmLoading(chatbut, instance);
6277
+
aiomatic_generator_working = false;
6278
+
if (typeof eventGenerator !== 'undefined') {
6279
+
eventGenerator.close();
6280
+
jQuery('#aistopbut' + instance).hide();
6281
+
}
6282
+
}
6283
+
});
6284
+
}
6285
+
function handleRefusalDone(e) {
6286
+
console.error('The AI refused to respond:', JSON.stringify(e.data));
6287
+
aiomaticRmLoading(chatbut, instance);
6288
+
aiomatic_generator_working = false;
6289
+
jQuery('#aistopbut' + instance).hide();
6290
+
eventGenerator.close();
6291
+
}
6292
+
6293
+
function handleResponsesMessageFailedEvent(e)
6294
+
{
6295
+
console.log('Responses API failed: ' + JSON.stringify(e));
6296
+
aiomaticRmLoading(chatbut, instance);
6297
+
aiomatic_generator_working = false;
6298
+
eventGenerator.close();
6299
+
jQuery('#aistopbut' + instance).hide();
6300
+
return;
6301
+
}
6302
+
function handleResponsesMessageStopEvent(e)
6303
+
{
6304
+
aiomaticRmLoading(chatbut, instance);
6305
+
aiomatic_generator_working = false;
6306
+
eventGenerator.close();
6307
+
jQuery('#aistopbut' + instance).hide();
6308
+
var x_input_text = jQuery('#aiomatic_chat_history' + instance).html();
6309
+
if((persistent != 'off' && persistent != '0' && persistent != '') && aiomatic_chat_ajax_object.user_id != '0' && error_generated == '')
6310
+
{
6311
+
var save_persistent = x_input_text;
6312
+
if(persistent == 'vector')
6313
+
{
6314
+
save_persistent = user_question;
6315
+
}
6316
+
var saving_index = '';
6317
+
var main_index = '';
6318
+
if(persistent == 'history')
6319
+
{
6320
+
saving_index = jQuery('#chat-log-identifier' + instance).val();
6321
+
main_index = jQuery('#chat-main-identifier' + instance).val();
6322
+
}
6323
+
jQuery.ajax({
6324
+
type: 'POST',
6325
+
url: aiomatic_chat_ajax_object.ajax_url,
6326
+
data: {
6327
+
action: 'aiomatic_user_meta_save',
6328
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
6329
+
persistent: persistent,
6330
+
thread_id: aiomatic_chat_ajax_object.thread_id,
6331
+
x_input_text: save_persistent,
6332
+
user_id: aiomatic_chat_ajax_object.user_id,
6333
+
saving_index: saving_index,
6334
+
main_index: main_index
6335
+
},
6336
+
success: function(result) {
6337
+
if(result.name && result.msg)
6338
+
{
6339
+
var logsdrop = jQuery('#chat-logs-dropdown' + instance);
6340
+
if(logsdrop)
6341
+
{
6342
+
var newChatLogItem = jQuery('<div class="chat-log-item" id="chat-log-item' + saving_index + '" data-id="' + saving_index + '" onclick="aiomatic_trigger_chat_logs(\'' + saving_index + '\', \'' + instance + '\')">' + result.name + '<span onclick="aiomatic_remove_chat_logs(event, \'' + saving_index + '\', \'' + instance + '\');" class="aiomatic-remove-item">X</span></div>');
6343
+
var chatLogNew = logsdrop.find('.chat-log-new');
6344
+
if (chatLogNew.length)
6345
+
{
6346
+
var nextSibling = chatLogNew.next();
6347
+
if (nextSibling.length && nextSibling.hasClass('date-group-label'))
6348
+
{
6349
+
newChatLogItem.insertAfter(nextSibling);
6350
+
}
6351
+
else
6352
+
{
6353
+
newChatLogItem.insertAfter(chatLogNew);
6354
+
}
6355
+
}
6356
+
else
6357
+
{
6358
+
logsdrop.append(newChatLogItem);
6359
+
}
6360
+
}
6361
+
}
6362
+
},
6363
+
error: function(error) {
6364
+
console.log('Error while saving persistent user log: ' + error.responseText);
6365
+
},
6366
+
});
6367
+
}
6368
+
if(error_generated == '')
6369
+
{
6370
+
jQuery.ajax({
6371
+
type: 'POST',
6372
+
url: aiomatic_chat_ajax_object.ajax_url,
6373
+
data: {
6374
+
action: 'aiomatic_record_user_usage',
6375
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
6376
+
user_id: aiomatic_chat_ajax_object.user_id,
6377
+
input_text: input_text,
6378
+
response_text: response_data,
6379
+
model: model,
6380
+
temp: temp,
6381
+
vision_file: vision_file,
6382
+
user_token_cap_per_day: aiomatic_chat_ajax_object.user_token_cap_per_day,
6383
+
source: 'chat'
6384
+
},
6385
+
success: function()
6386
+
{
6387
+
},
6388
+
error: function(error) {
6389
+
console.log('Error while saving user data: ' + error.responseText);
6390
+
},
6391
+
});
6392
+
}
6393
+
if(error_generated == '')
6394
+
{
6395
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6396
+
}
6397
+
var has_speech = false;
6398
+
if(aiomatic_chat_ajax_object.receive_message_sound != '')
6399
+
{
6400
+
var snd = new Audio(aiomatic_chat_ajax_object.receive_message_sound);
6401
+
snd.play();
6402
+
}
6403
+
if(error_generated == '' && !jQuery('.aiomatic-gg-unmute').length)
6404
+
{
6405
+
if(aiomatic_chat_ajax_object.text_speech == 'elevenlabs')
6406
+
{
6407
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
6408
+
response_data = aiomatic_stripHtmlTags(response_data);
6409
+
if(response_data != '')
6410
+
{
6411
+
has_speech = true;
6412
+
let speechData = new FormData();
6413
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
6414
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
6415
+
speechData.append('x_input_text', response_data);
6416
+
speechData.append('action', 'aiomatic_get_elevenlabs_voice_chat');
6417
+
var speechRequest = new XMLHttpRequest();
6418
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
6419
+
speechRequest.responseType = "arraybuffer";
6420
+
speechRequest.ontimeout = () => {
6421
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
6422
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6423
+
aiomaticRmLoading(chatbut, instance);
6424
+
aiomatic_generator_working = false;
6425
+
};
6426
+
speechRequest.onerror = function ()
6427
+
{
6428
+
console.error("Network Error");
6429
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6430
+
aiomaticRmLoading(chatbut, instance);
6431
+
aiomatic_generator_working = false;
6432
+
};
6433
+
speechRequest.onabort = function ()
6434
+
{
6435
+
console.error("The request was aborted.");
6436
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6437
+
aiomaticRmLoading(chatbut, instance);
6438
+
aiomatic_generator_working = false;
6439
+
};
6440
+
speechRequest.onload = function () {
6441
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
6442
+
var fr = new FileReader();
6443
+
fr.onload = function () {
6444
+
var fileText = this.result;
6445
+
try {
6446
+
var errorMessage = JSON.parse(fileText);
6447
+
console.log('ElevenLabs API failed: ' + errorMessage.msg);
6448
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6449
+
aiomaticRmLoading(chatbut, instance);
6450
+
aiomatic_generator_working = false;
6451
+
} catch (errorBlob) {
6452
+
var blobUrl = URL.createObjectURL(blob);
6453
+
var audioElement = document.createElement('audio');
6454
+
audioElement.src = blobUrl;
6455
+
audioElement.controls = true;
6456
+
audioElement.style.marginTop = "2px";
6457
+
audioElement.style.width = "100%";
6458
+
audioElement.id = 'audio-element-' + instance;
6459
+
audioElement.addEventListener("error", function(event) {
6460
+
console.error("Error loading or playing the audio: ", event);
6461
+
});
6462
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
6463
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
6464
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
6465
+
{
6466
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
6467
+
var waveform = WaveSurfer.create({
6468
+
container: '#waveform-container' + instance,
6469
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
6470
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
6471
+
backend: 'MediaElement',
6472
+
height: 60,
6473
+
barWidth: 2,
6474
+
responsive: true, mediaControls: false, interact: false
6475
+
});
6476
+
waveform.setMuted(true);
6477
+
waveform.load(blobUrl);
6478
+
waveform.on('ready', function () {
6479
+
waveform.play();
6480
+
});
6481
+
audioElement.addEventListener('play', function () {
6482
+
waveform.play();
6483
+
});
6484
+
audioElement.addEventListener('pause', function () {
6485
+
waveform.pause();
6486
+
});
6487
+
}
6488
+
else
6489
+
{
6490
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6491
+
}
6492
+
audioElement.play();
6493
+
aiomaticRmLoading(chatbut, instance);
6494
+
aiomatic_generator_working = false;
6495
+
}
6496
+
}
6497
+
fr.readAsText(blob);
6498
+
}
6499
+
speechRequest.send(speechData);
6500
+
}
6501
+
}
6502
+
else
6503
+
{
6504
+
if(aiomatic_chat_ajax_object.text_speech == 'openai')
6505
+
{
6506
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
6507
+
response_data = aiomatic_stripHtmlTags(response_data);
6508
+
if(response_data != '')
6509
+
{
6510
+
has_speech = true;
6511
+
let speechData = new FormData();
6512
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
6513
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
6514
+
speechData.append('x_input_text', response_data);
6515
+
speechData.append('action', 'aiomatic_get_openai_voice_chat');
6516
+
var speechRequest = new XMLHttpRequest();
6517
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
6518
+
speechRequest.responseType = "arraybuffer";
6519
+
speechRequest.ontimeout = () => {
6520
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
6521
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6522
+
aiomaticRmLoading(chatbut, instance);
6523
+
aiomatic_generator_working = false;
6524
+
};
6525
+
speechRequest.onerror = function ()
6526
+
{
6527
+
console.error("Network Error");
6528
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6529
+
aiomaticRmLoading(chatbut, instance);
6530
+
aiomatic_generator_working = false;
6531
+
};
6532
+
speechRequest.onabort = function ()
6533
+
{
6534
+
console.error("The request was aborted.");
6535
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6536
+
aiomaticRmLoading(chatbut, instance);
6537
+
aiomatic_generator_working = false;
6538
+
};
6539
+
speechRequest.onload = function () {
6540
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
6541
+
var fr = new FileReader();
6542
+
fr.onload = function () {
6543
+
var fileText = this.result;
6544
+
try {
6545
+
var errorMessage = JSON.parse(fileText);
6546
+
console.log('OpenAI TTS API failed: ' + errorMessage.msg);
6547
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6548
+
aiomaticRmLoading(chatbut, instance);
6549
+
aiomatic_generator_working = false;
6550
+
} catch (errorBlob) {
6551
+
var blobUrl = URL.createObjectURL(blob);
6552
+
var audioElement = document.createElement('audio');
6553
+
audioElement.src = blobUrl;
6554
+
audioElement.controls = true;
6555
+
audioElement.style.marginTop = "2px";
6556
+
audioElement.style.width = "100%";
6557
+
audioElement.id = 'audio-element-' + instance;
6558
+
audioElement.addEventListener("error", function(event) {
6559
+
console.error("Error loading or playing the audio: ", event);
6560
+
});
6561
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
6562
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
6563
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
6564
+
{
6565
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
6566
+
var waveform = WaveSurfer.create({
6567
+
container: '#waveform-container' + instance,
6568
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
6569
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
6570
+
backend: 'MediaElement',
6571
+
height: 60,
6572
+
barWidth: 2,
6573
+
responsive: true, mediaControls: false, interact: false
6574
+
});
6575
+
waveform.setMuted(true);
6576
+
waveform.load(blobUrl);
6577
+
waveform.on('ready', function () {
6578
+
waveform.play();
6579
+
});
6580
+
audioElement.addEventListener('play', function () {
6581
+
waveform.play();
6582
+
});
6583
+
audioElement.addEventListener('pause', function () {
6584
+
waveform.pause();
6585
+
});
6586
+
}
6587
+
else
6588
+
{
6589
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6590
+
}
6591
+
audioElement.play();
6592
+
aiomaticRmLoading(chatbut, instance);
6593
+
aiomatic_generator_working = false;
6594
+
}
6595
+
}
6596
+
fr.readAsText(blob);
6597
+
}
6598
+
speechRequest.send(speechData);
6599
+
}
6600
+
}
6601
+
else
6602
+
{
6603
+
if(aiomatic_chat_ajax_object.text_speech == 'google')
6604
+
{
6605
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
6606
+
response_data = aiomatic_stripHtmlTags(response_data);
6607
+
if(response_data != '')
6608
+
{
6609
+
has_speech = true;
6610
+
let speechData = new FormData();
6611
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
6612
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
6613
+
speechData.append('x_input_text', response_data);
6614
+
speechData.append('action', 'aiomatic_get_google_voice_chat');
6615
+
var speechRequest = new XMLHttpRequest();
6616
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
6617
+
speechRequest.ontimeout = () => {
6618
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
6619
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6620
+
aiomaticRmLoading(chatbut, instance);
6621
+
aiomatic_generator_working = false;
6622
+
};
6623
+
speechRequest.onerror = function ()
6624
+
{
6625
+
console.error("Network Error");
6626
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6627
+
aiomaticRmLoading(chatbut, instance);
6628
+
aiomatic_generator_working = false;
6629
+
};
6630
+
speechRequest.onabort = function ()
6631
+
{
6632
+
console.error("The request was aborted.");
6633
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6634
+
aiomaticRmLoading(chatbut, instance);
6635
+
aiomatic_generator_working = false;
6636
+
};
6637
+
speechRequest.onload = function () {
6638
+
var result = speechRequest.responseText;
6639
+
try {
6640
+
var jsonresult = JSON.parse(result);
6641
+
if(jsonresult.status === 'success'){
6642
+
var byteCharacters = atob(jsonresult.audio);
6643
+
const byteNumbers = new Array(byteCharacters.length);
6644
+
for (let i = 0; i < byteCharacters.length; i++) {
6645
+
byteNumbers[i] = byteCharacters.charCodeAt(i);
6646
+
}
6647
+
const byteArray = new Uint8Array(byteNumbers);
6648
+
const blob = new Blob([byteArray], {type: 'audio/mp3'});
6649
+
var blobUrl = URL.createObjectURL(blob);
6650
+
var audioElement = document.createElement('audio');
6651
+
audioElement.src = blobUrl;
6652
+
audioElement.controls = true;
6653
+
audioElement.style.marginTop = "2px";
6654
+
audioElement.style.width = "100%";
6655
+
audioElement.id = 'audio-element-' + instance;
6656
+
audioElement.addEventListener("error", function(event) {
6657
+
console.error("Error loading or playing the audio: ", event);
6658
+
});
6659
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
6660
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
6661
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
6662
+
{
6663
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
6664
+
var waveform = WaveSurfer.create({
6665
+
container: '#waveform-container' + instance,
6666
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
6667
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
6668
+
backend: 'MediaElement',
6669
+
height: 60,
6670
+
barWidth: 2,
6671
+
responsive: true, mediaControls: false, interact: false
6672
+
});
6673
+
waveform.setMuted(true);
6674
+
waveform.load(blobUrl);
6675
+
waveform.on('ready', function () {
6676
+
waveform.play();
6677
+
});
6678
+
audioElement.addEventListener('play', function () {
6679
+
waveform.play();
6680
+
});
6681
+
audioElement.addEventListener('pause', function () {
6682
+
waveform.pause();
6683
+
});
6684
+
}
6685
+
else
6686
+
{
6687
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6688
+
}
6689
+
audioElement.play();
6690
+
aiomaticRmLoading(chatbut, instance);
6691
+
aiomatic_generator_working = false;
6692
+
}
6693
+
else{
6694
+
var errorMessageDetail = 'Google: ' + jsonresult.msg;
6695
+
console.log('Google Text-to-Speech error: ' + errorMessageDetail);
6696
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6697
+
aiomaticRmLoading(chatbut, instance);
6698
+
aiomatic_generator_working = false;
6699
+
}
6700
+
}
6701
+
catch (errorSpeech){
6702
+
console.log('Exception in Google Text-to-Speech API: ' + errorSpeech);
6703
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6704
+
aiomaticRmLoading(chatbut, instance);
6705
+
aiomatic_generator_working = false;
6706
+
}
6707
+
}
6708
+
speechRequest.send(speechData);
6709
+
}
6710
+
}
6711
+
else
6712
+
{
6713
+
if(aiomatic_chat_ajax_object.text_speech == 'did')
6714
+
{
6715
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
6716
+
response_data = aiomatic_stripHtmlTags(response_data);
6717
+
if(response_data != '')
6718
+
{
6719
+
has_speech = true;
6720
+
let speechData = new FormData();
6721
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
6722
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
6723
+
speechData.append('x_input_text', response_data);
6724
+
speechData.append('action', 'aiomatic_get_d_id_video_chat');
6725
+
var speechRequest = new XMLHttpRequest();
6726
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
6727
+
speechRequest.ontimeout = () => {
6728
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
6729
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6730
+
aiomaticRmLoading(chatbut, instance);
6731
+
aiomatic_generator_working = false;
6732
+
};
6733
+
speechRequest.onerror = function ()
6734
+
{
6735
+
console.error("Network Error");
6736
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6737
+
aiomaticRmLoading(chatbut, instance);
6738
+
aiomatic_generator_working = false;
6739
+
};
6740
+
speechRequest.onabort = function ()
6741
+
{
6742
+
console.error("The request was aborted.");
6743
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6744
+
aiomaticRmLoading(chatbut, instance);
6745
+
aiomatic_generator_working = false;
6746
+
};
6747
+
speechRequest.onload = function () {
6748
+
var result = speechRequest.responseText;
6749
+
try
6750
+
{
6751
+
var jsonresult = JSON.parse(result);
6752
+
if(jsonresult.status === 'success')
6753
+
{
6754
+
var videoURL = '<video class="ai_video" autoplay="autoplay" controls="controls"><source src="' + jsonresult.video + '" type="video/mp4"></video>';
6755
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-video">' + videoURL + '</div>');
6756
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6757
+
aiomaticRmLoading(chatbut, instance);
6758
+
aiomatic_generator_working = false;
6759
+
}
6760
+
else
6761
+
{
6762
+
var errorMessageDetail = 'D-ID: ' + jsonresult.msg;
6763
+
console.log('D-ID Text-to-video error: ' + errorMessageDetail);
6764
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6765
+
aiomaticRmLoading(chatbut, instance);
6766
+
aiomatic_generator_working = false;
6767
+
}
6768
+
}
6769
+
catch (errorSpeech){
6770
+
console.log('Exception in D-ID Text-to-video API: ' + errorSpeech);
6771
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6772
+
aiomaticRmLoading(chatbut, instance);
6773
+
aiomatic_generator_working = false;
6774
+
}
6775
+
}
6776
+
speechRequest.send(speechData);
6777
+
}
6778
+
}
6779
+
else
6780
+
{
6781
+
if(aiomatic_chat_ajax_object.text_speech == 'didstream')
6782
+
{
6783
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
6784
+
response_data = aiomatic_stripHtmlTags(response_data);
6785
+
if(response_data != '')
6786
+
{
6787
+
if(avatarImageUrl != '' && did_app_id != '')
6788
+
{
6789
+
if(streamingEpicFail === false)
6790
+
{
6791
+
has_speech = true;
6792
+
myStreamObject.talkToDidStream(response_data);
6793
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6794
+
aiomatic_generator_working = false;
6795
+
}
6796
+
}
6797
+
}
6798
+
}
6799
+
else
6800
+
{
6801
+
if(aiomatic_chat_ajax_object.text_speech == 'azure')
6802
+
{
6803
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
6804
+
response_data = aiomatic_stripHtmlTags(response_data);
6805
+
if(response_data != '')
6806
+
{
6807
+
if(azure_speech_id != '')
6808
+
{
6809
+
if(streamingEpicFail === false)
6810
+
{
6811
+
has_speech = true;
6812
+
var ttsvoice = aiomatic_chat_ajax_object.azure_voice;
6813
+
var personalVoiceSpeakerProfileID = aiomatic_chat_ajax_object.azure_voice_profile;
6814
+
aiomaticRmLoading(chatbut, instance);
6815
+
azureSpeakText(response_data, ttsvoice, personalVoiceSpeakerProfileID);
6816
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6817
+
aiomatic_generator_working = false;
6818
+
}
6819
+
}
6820
+
}
6821
+
}
6822
+
else
6823
+
{
6824
+
if(aiomatic_chat_ajax_object.text_speech == 'free')
6825
+
{
6826
+
var T2S;
6827
+
if("speechSynthesis" in window || speechSynthesis)
6828
+
{
6829
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
6830
+
response_data = aiomatic_stripHtmlTags(response_data);
6831
+
if(response_data != '')
6832
+
{
6833
+
T2S = window.speechSynthesis || speechSynthesis;
6834
+
var utter = new SpeechSynthesisUtterance(response_data);
6835
+
var voiceSetting = aiomatic_chat_ajax_object.free_voice.split(";");
6836
+
var desiredVoiceName = voiceSetting[0].trim();
6837
+
var desiredLang = voiceSetting[1].trim();
6838
+
var voices = T2S.getVoices();
6839
+
var selectedVoice = voices.find(function(voice) {
6840
+
return voice.name === desiredVoiceName && voice.lang === desiredLang;
6841
+
});
6842
+
if (selectedVoice) {
6843
+
utter.voice = selectedVoice;
6844
+
utter.lang = selectedVoice.lang;
6845
+
}
6846
+
else
6847
+
{
6848
+
utter.lang = desiredLang;
6849
+
}
6850
+
T2S.speak(utter);
6851
+
}
6852
+
}
6853
+
}
6854
+
}
6855
+
}
6856
+
}
6857
+
}
6858
+
}
6859
+
}
6860
+
}
6861
+
if(has_speech === false)
6862
+
{
6863
+
if(error_generated == '')
6864
+
{
6865
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
6866
+
}
6867
+
aiomaticRmLoading(chatbut, instance);
6868
+
aiomatic_generator_working = false;
6869
+
}
6870
+
return;
6871
+
}
6872
+
function handleMessageStopEvent(e)
6873
+
{
6874
+
aiomaticRmLoading(chatbut, instance);
6875
+
aiomatic_generator_working = false;
6876
+
eventGenerator.close();
6877
+
jQuery('#aistopbut' + instance).hide();
6878
+
return;
6879
+
}
6880
+
function handleMessageErrorEvent(e)
6881
+
{
6882
+
console.log('Error in Event running: ' + JSON.stringify(e));
6883
+
aiomaticRmLoading(chatbut, instance);
6884
+
aiomatic_generator_working = false;
6885
+
eventGenerator.close();
6886
+
jQuery('#aistopbut' + instance).hide();
6887
+
return;
6888
+
}
6889
+
function threadCreatedEventHandler(e) {
6890
+
try
6891
+
{
6892
+
var data = JSON.parse(e.data);
6893
+
}
6894
+
catch (errorSpeech){
6895
+
}
6896
+
//console.log('Thread created:', data);
6897
+
}
6898
+
function threadRunCreatedEventHandler(e) {
6899
+
try
6900
+
{
6901
+
var data = JSON.parse(e.data);
6902
+
run_id = data.id;
6903
+
th_id = data.thread_id;
6904
+
}
6905
+
catch (errorSpeech){
6906
+
}
6907
+
//console.log('Run created:', data);
6908
+
}
6909
+
function threadRunQueuedEventHandler(e) {
6910
+
//console.log('Run queued:', data);
6911
+
}
6912
+
function threadRunInProgressEventHandler(e) {
6913
+
//console.log('Run in_progress:', data);
6914
+
}
6915
+
function threadRunRequiresActionEventHandler(e) {
6916
+
//console.log('Run requires_action:', data);
6917
+
if (func_calls > 0)
6918
+
{
6919
+
jQuery.ajax({
6920
+
type: 'POST',
6921
+
async: false,
6922
+
url: aiomatic_chat_ajax_object.ajax_url,
6923
+
data: {
6924
+
action: 'aiomatic_call_ai_function',
6925
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
6926
+
func_call: func_call
6927
+
},
6928
+
success: function(result)
6929
+
{
6930
+
if (typeof result !== "object" || result === null)
6931
+
{
6932
+
try
6933
+
{
6934
+
result = JSON.parse(result);
6935
+
}
6936
+
catch (error) {}
6937
+
}
6938
+
if(result.scope == 'fail')
6939
+
{
6940
+
console.log('Error while calling parsing functions: ' + result);
6941
+
hasFinishReason = true;
6942
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
6943
+
aiomaticRmLoading(chatbut, instance);
6944
+
aiomatic_generator_working = false;
6945
+
if (typeof eventGenerator !== 'undefined')
6946
+
{
6947
+
eventGenerator.close();
6948
+
jQuery('#aistopbut' + instance).hide();
6949
+
}
6950
+
return;
6951
+
}
6952
+
else
6953
+
{
6954
+
if(result.scope == 'response')
6955
+
{
6956
+
console.log('Recalling AI stream chat');
6957
+
if (typeof eventGenerator !== 'undefined')
6958
+
{
6959
+
eventGenerator.close();
6960
+
jQuery('#aistopbut' + instance).hide();
6961
+
}
6962
+
if(aiomatic_chat_ajax_object.enable_god_mode == '')
6963
+
{
6964
+
aiomatic_chat_ajax_object.enable_god_mode = 'off';
6965
+
}
6966
+
var internet_permission = aiomatic_chat_ajax_object.internet_access;
6967
+
if(jQuery('#aiomatic-globe-overlay' + instance).hasClass('aiomatic-globe-bar') && jQuery('#aiomatic-globe-overlay' + instance).is(':visible'))
6968
+
{
6969
+
internet_permission = 'disabled';
6970
+
}
6971
+
eventURL = aiomatic_chat_ajax_object.stream_url;
6972
+
if(pdf_data != '')
6973
+
{
6974
+
eventURL += '&pdf_data=' + encodeURIComponent(pdf_data);
6975
+
}
6976
+
if(file_data != '')
6977
+
{
6978
+
eventURL += '&file_data=' + encodeURIComponent(file_data);
6979
+
}
6980
+
if(aiomatic_chat_ajax_object.user_token_cap_per_day != '')
6981
+
{
6982
+
eventURL += '&user_token_cap_per_day=' + encodeURIComponent(aiomatic_chat_ajax_object.user_token_cap_per_day);
6983
+
}
6984
+
if(aiomatic_chat_ajax_object.user_id != '')
6985
+
{
6986
+
eventURL += '&user_id=' + encodeURIComponent(aiomatic_chat_ajax_object.user_id);
6987
+
}
6988
+
if(aiomatic_chat_ajax_object.frequency != '')
6989
+
{
6990
+
eventURL += '&frequency=' + encodeURIComponent(aiomatic_chat_ajax_object.frequency);
6991
+
}
6992
+
if(aiomatic_chat_ajax_object.store_data != '')
6993
+
{
6994
+
eventURL += '&store_data=' + encodeURIComponent(aiomatic_chat_ajax_object.store_data);
6995
+
}
6996
+
if(aiomatic_chat_ajax_object.presence != '')
6997
+
{
6998
+
eventURL += '&presence=' + encodeURIComponent(aiomatic_chat_ajax_object.presence);
6999
+
}
7000
+
if(aiomatic_chat_ajax_object.top_p != '')
7001
+
{
7002
+
eventURL += '&top_p=' + encodeURIComponent(aiomatic_chat_ajax_object.top_p);
7003
+
}
7004
+
if(aiomatic_chat_ajax_object.temp != '')
7005
+
{
7006
+
eventURL += '&temp=' + encodeURIComponent(aiomatic_chat_ajax_object.temp);
7007
+
}
7008
+
if(aiomatic_chat_ajax_object.model != '')
7009
+
{
7010
+
eventURL += '&model=' + encodeURIComponent(aiomatic_chat_ajax_object.model);
7011
+
}
7012
+
if(ai_assistant_id != '')
7013
+
{
7014
+
eventURL += '&assistant_id=' + encodeURIComponent(ai_assistant_id);
7015
+
}
7016
+
if(th_id != '')
7017
+
{
7018
+
eventURL += '&thread_id=' + encodeURIComponent(th_id);
7019
+
}
7020
+
if(remember_string != '')
7021
+
{
7022
+
eventURL += '&remember_string=' + encodeURIComponent(remember_string);
7023
+
}
7024
+
if(is_modern_gpt != '')
7025
+
{
7026
+
eventURL += '&is_modern_gpt=' + encodeURIComponent(is_modern_gpt);
7027
+
}
7028
+
if(internet_permission != '')
7029
+
{
7030
+
eventURL += '&internet_access=' + encodeURIComponent(internet_permission);
7031
+
}
7032
+
if(aiomatic_chat_ajax_object.embeddings != '')
7033
+
{
7034
+
eventURL += '&embeddings=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings);
7035
+
}
7036
+
if(aiomatic_chat_ajax_object.embeddings_namespace != '')
7037
+
{
7038
+
eventURL += '&embeddings_namespace=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings_namespace);
7039
+
}
7040
+
if(user_question != '')
7041
+
{
7042
+
eventURL += '&user_question=' + encodeURIComponent(user_question);
7043
+
}
7044
+
if(enable_god_mode != '')
7045
+
{
7046
+
eventURL += '&enable_god_mode=' + encodeURIComponent(enable_god_mode);
7047
+
}
7048
+
if(mcp_servers != '')
7049
+
{
7050
+
eventURL += '&mcp_servers=' + encodeURIComponent(mcp_servers);
7051
+
}
7052
+
if(aiomatic_chat_ajax_object.bots_data && aiomatic_chat_ajax_object.strip_botname == '1')
7053
+
{
7054
+
aiomatic_chat_ajax_object.bots_data.forEach((relement) => input_text = input_text.replace('@' + relement.name, ''));
7055
+
}
7056
+
eventURL += '&input_text=' + encodeURIComponent(input_text);
7057
+
if(vision_file != '')
7058
+
{
7059
+
eventURL += '&vision_file=' + encodeURIComponent(vision_file);
7060
+
}
7061
+
var fnrez = JSON.stringify(result.data);
7062
+
eventURL += '&functions_result=' + encodeURIComponent(fnrez);
7063
+
if(run_id != '')
7064
+
{
7065
+
eventURL += '&run_id=' + encodeURIComponent(run_id);
7066
+
}
7067
+
if(eventURL.length > 2080)
7068
+
{
7069
+
console.log('URL too long, using alternative processing method');
7070
+
var unid = "id" + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
7071
+
aiChatUploadDataomatic(aiomatic_chat_ajax_object, unid, input_text, remember_string, user_question, fnrez);
7072
+
eventURL = aiomatic_chat_ajax_object.stream_url;
7073
+
eventURL += '&input_text=0&remember_string=0&user_question=0&functions_result=0';
7074
+
if(pdf_data != '')
7075
+
{
7076
+
eventURL += '&pdf_data=' + encodeURIComponent(pdf_data);
7077
+
}
7078
+
if(file_data != '')
7079
+
{
7080
+
eventURL += '&file_data=' + encodeURIComponent(file_data);
7081
+
}
7082
+
if(aiomatic_chat_ajax_object.user_token_cap_per_day != '')
7083
+
{
7084
+
eventURL += '&user_token_cap_per_day=' + encodeURIComponent(aiomatic_chat_ajax_object.user_token_cap_per_day);
7085
+
}
7086
+
if(aiomatic_chat_ajax_object.user_id != '')
7087
+
{
7088
+
eventURL += '&user_id=' + encodeURIComponent(aiomatic_chat_ajax_object.user_id);
7089
+
}
7090
+
if(aiomatic_chat_ajax_object.frequency != '')
7091
+
{
7092
+
eventURL += '&frequency=' + encodeURIComponent(aiomatic_chat_ajax_object.frequency);
7093
+
}
7094
+
if(aiomatic_chat_ajax_object.store_data != '')
7095
+
{
7096
+
eventURL += '&store_data=' + encodeURIComponent(aiomatic_chat_ajax_object.store_data);
7097
+
}
7098
+
if(aiomatic_chat_ajax_object.presence != '')
7099
+
{
7100
+
eventURL += '&presence=' + encodeURIComponent(aiomatic_chat_ajax_object.presence);
7101
+
}
7102
+
if(aiomatic_chat_ajax_object.top_p != '')
7103
+
{
7104
+
eventURL += '&top_p=' + encodeURIComponent(aiomatic_chat_ajax_object.top_p);
7105
+
}
7106
+
if(aiomatic_chat_ajax_object.temp != '')
7107
+
{
7108
+
eventURL += '&temp=' + encodeURIComponent(aiomatic_chat_ajax_object.temp);
7109
+
}
7110
+
if(aiomatic_chat_ajax_object.model != '')
7111
+
{
7112
+
eventURL += '&model=' + encodeURIComponent(aiomatic_chat_ajax_object.model);
7113
+
}
7114
+
if(ai_assistant_id != '')
7115
+
{
7116
+
eventURL += '&assistant_id=' + encodeURIComponent(ai_assistant_id);
7117
+
}
7118
+
if(th_id != '')
7119
+
{
7120
+
eventURL += '&thread_id=' + encodeURIComponent(th_id);
7121
+
}
7122
+
if(is_modern_gpt != '')
7123
+
{
7124
+
eventURL += '&is_modern_gpt=' + encodeURIComponent(is_modern_gpt);
7125
+
}
7126
+
if(internet_permission != '')
7127
+
{
7128
+
eventURL += '&internet_access=' + encodeURIComponent(internet_permission);
7129
+
}
7130
+
if(aiomatic_chat_ajax_object.embeddings != '')
7131
+
{
7132
+
eventURL += '&embeddings=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings);
7133
+
}
7134
+
if(aiomatic_chat_ajax_object.embeddings_namespace != '')
7135
+
{
7136
+
eventURL += '&embeddings_namespace=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings_namespace);
7137
+
}
7138
+
if(enable_god_mode != '')
7139
+
{
7140
+
eventURL += '&enable_god_mode=' + encodeURIComponent(enable_god_mode);
7141
+
}
7142
+
if(mcp_servers != '')
7143
+
{
7144
+
eventURL += '&mcp_servers=' + encodeURIComponent(mcp_servers);
7145
+
}
7146
+
if(vision_file != '')
7147
+
{
7148
+
eventURL += '&vision_file=' + encodeURIComponent(vision_file);
7149
+
}
7150
+
if(run_id != '')
7151
+
{
7152
+
eventURL += '&run_id=' + encodeURIComponent(run_id);
7153
+
}
7154
+
eventURL += '&bufferid=' + encodeURIComponent(unid);
7155
+
}
7156
+
func_call = {
7157
+
init_data: {
7158
+
pdf_data: pdf_data,
7159
+
file_data: file_data,
7160
+
user_token_cap_per_day: aiomatic_chat_ajax_object.user_token_cap_per_day,
7161
+
user_id: aiomatic_chat_ajax_object.user_id,
7162
+
store_data: aiomatic_chat_ajax_object.store_data,
7163
+
frequency: aiomatic_chat_ajax_object.frequency,
7164
+
presence: aiomatic_chat_ajax_object.presence,
7165
+
top_p: aiomatic_chat_ajax_object.top_p,
7166
+
temp: aiomatic_chat_ajax_object.temp,
7167
+
model: aiomatic_chat_ajax_object.model,
7168
+
input_text: input_text,
7169
+
remember_string: remember_string,
7170
+
is_modern_gpt: is_modern_gpt,
7171
+
user_question: user_question
7172
+
},
7173
+
};
7174
+
try
7175
+
{
7176
+
eventGenerator = new EventSource(eventURL);
7177
+
}
7178
+
catch(e)
7179
+
{
7180
+
console.log('Error in Event startup: ' + e);
7181
+
}
7182
+
eventGenerator.onerror = handleErrorEvent2;
7183
+
hasFinishReason = false;
7184
+
if(ai_assistant_id != '')
7185
+
{
7186
+
eventGenerator.addEventListener('thread.created', threadCreatedEventHandler);
7187
+
eventGenerator.addEventListener('thread.run.created', threadRunCreatedEventHandler);
7188
+
eventGenerator.addEventListener('thread.run.queued', threadRunQueuedEventHandler);
7189
+
eventGenerator.addEventListener('thread.run.in_progress', threadRunInProgressEventHandler);
7190
+
eventGenerator.addEventListener('thread.run.requires_action', threadRunRequiresActionEventHandler);
7191
+
eventGenerator.addEventListener('thread.run.completed', threadRunCompletedEventHandler);
7192
+
eventGenerator.addEventListener('thread.run.failed', threadRunFailedEventHandler);
7193
+
eventGenerator.addEventListener('thread.run.cancelling', threadRunCancellingEventHandler);
7194
+
eventGenerator.addEventListener('thread.run.cancelled', threadRunCancelledEventHandler);
7195
+
eventGenerator.addEventListener('thread.run.expired', threadRunExpiredEventHandler);
7196
+
eventGenerator.addEventListener('thread.run.step.created', threadRunStepCreatedEventHandler);
7197
+
eventGenerator.addEventListener('thread.run.step.in_progress', threadRunStepInProgressEventHandler);
7198
+
eventGenerator.addEventListener('thread.run.step.delta', threadRunStepDeltaEventHandler);
7199
+
eventGenerator.addEventListener('thread.run.step.completed', threadRunStepCompletedEventHandler);
7200
+
eventGenerator.addEventListener('thread.run.step.failed', threadRunStepFailedEventHandler);
7201
+
eventGenerator.addEventListener('thread.run.step.cancelled', threadRunStepCancelledEventHandler);
7202
+
eventGenerator.addEventListener('thread.run.step.expired', threadRunStepExpiredEventHandler);
7203
+
eventGenerator.addEventListener('thread.message.created', threadMessageCreatedEventHandler);
7204
+
eventGenerator.addEventListener('thread.message.in_progress', threadMessageInProgressEventHandler);
7205
+
eventGenerator.addEventListener('thread.message.delta', threadMessageDeltaEventHandler);
7206
+
eventGenerator.addEventListener('thread.message.incomplete', threadMessageIncompleteEventHandler);
7207
+
eventGenerator.addEventListener('thread.message.completed', threadMessageCompletedEventHandler);
7208
+
}
7209
+
else
7210
+
{
7211
+
eventGenerator.onmessage = handleMessageEvent;
7212
+
eventGenerator.addEventListener('content_block_delta', handleContentBlockDelta);
7213
+
eventGenerator.addEventListener('message_stop', handleMessageStopEvent);
7214
+
eventGenerator.addEventListener('completion', handleCompletionEvent);
7215
+
7216
+
eventGenerator.addEventListener('response.output_text.delta', handleContentBlockDeltaResponses);
7217
+
eventGenerator.addEventListener('response.completed', handleResponsesMessageStopEvent);
7218
+
eventGenerator.addEventListener('response.failed', handleResponsesMessageFailedEvent);
7219
+
eventGenerator.addEventListener('response.incomplete', function (event) {
7220
+
console.log('Incomplete message');
7221
+
});
7222
+
eventGenerator.addEventListener('error', handleMessageErrorEvent);
7223
+
7224
+
//eventGenerator.addEventListener('response.created', e => console.log('Response created'));
7225
+
//eventGenerator.addEventListener('response.in_progress', e => console.log('Response in progress'));
7226
+
7227
+
eventGenerator.addEventListener('response.output_item.added', handleOutputItemAdded);
7228
+
//eventGenerator.addEventListener('response.output_item.done', e => console.log('Output item done'));
7229
+
7230
+
//eventGenerator.addEventListener('response.content_part.added', e => console.log('Content part added'));
7231
+
//eventGenerator.addEventListener('response.content_part.done', e => console.log('Content part done'));
7232
+
7233
+
//eventGenerator.addEventListener('response.output_text.done', e => console.log('Output text done'));
7234
+
7235
+
//eventGenerator.addEventListener('response.output_text.annotation.added', e => console.log('Annotation added'));
7236
+
7237
+
//eventGenerator.addEventListener('response.refusal.delta', e => console.log('Refusal delta'));
7238
+
7239
+
//eventGenerator.addEventListener('response.reasoning_summary_part.added', e => console.log('Reasoning summary part added'));
7240
+
//eventGenerator.addEventListener('response.reasoning_summary_part.done', e => console.log('Reasoning summary part done'));
7241
+
7242
+
//eventGenerator.addEventListener('response.reasoning_summary_text.delta', e => console.log('Reasoning summary delta'));
7243
+
//eventGenerator.addEventListener('response.reasoning_summary_text.done', e => console.log('Reasoning summary done'));
7244
+
eventGenerator.addEventListener('response.refusal.done', handleRefusalDone);
7245
+
7246
+
eventGenerator.addEventListener('response.function_call_arguments.delta', handleFunctionCallArgumentsDelta);
7247
+
eventGenerator.addEventListener('response.function_call_arguments.done', handleFunctionCallArgumentsDone);
7248
+
7249
+
eventGenerator.addEventListener('response.file_search_call.in_progress', e => console.log('File search in progress'));
7250
+
eventGenerator.addEventListener('response.file_search_call.searching', e => console.log('File search searching'));
7251
+
eventGenerator.addEventListener('response.file_search_call.completed', e => console.log('File search completed'));
7252
+
7253
+
eventGenerator.addEventListener('response.web_search_call.in_progress', e => console.log('Web search in progress'));
7254
+
eventGenerator.addEventListener('response.web_search_call.searching', e => console.log('Web search searching'));
7255
+
eventGenerator.addEventListener('response.web_search_call.completed', e => console.log('Web search completed'));
7256
+
}
7257
+
eventGenerator.addEventListener('error', function(e) {
7258
+
if (typeof result !== "object" || result === null)
7259
+
{
7260
+
try
7261
+
{
7262
+
var data = JSON.parse(e.data);
7263
+
console.error('Stream Error:', data);
7264
+
}
7265
+
catch (error) {
7266
+
console.error('Stream parse Error:', error);
7267
+
}
7268
+
}
7269
+
hasFinishReason = true;
7270
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7271
+
aiomaticRmLoading(chatbut, instance);
7272
+
aiomatic_generator_working = false;if (typeof eventGenerator !== 'undefined')
7273
+
{
7274
+
eventGenerator.close();
7275
+
jQuery('#aistopbut' + instance).hide();
7276
+
}
7277
+
});
7278
+
7279
+
eventGenerator.addEventListener('done', function(e) {
7280
+
console.log('Stream ended');
7281
+
hasFinishReason = true;
7282
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7283
+
aiomaticRmLoading(chatbut, instance);
7284
+
aiomatic_generator_working = false;if (typeof eventGenerator !== 'undefined')
7285
+
{
7286
+
eventGenerator.close();
7287
+
jQuery('#aistopbut' + instance).hide();
7288
+
}
7289
+
});
7290
+
}
7291
+
else
7292
+
{
7293
+
var appendx = '<div class="ai-wrapper">';
7294
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
7295
+
{
7296
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
7297
+
}
7298
+
appendx += '<div class="ai-bubble ai-other">' + result.data + '</div>';
7299
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
7300
+
{
7301
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
7302
+
}
7303
+
appendx += '</div>';
7304
+
if(result.scope == 'end_message')
7305
+
{
7306
+
const inputField = document.getElementById('aiomatic_chat_input' + instance);
7307
+
inputField.disabled = true;
7308
+
inputField.chatended = true;
7309
+
const speechButton = document.getElementById('openai-chat-speech-button' + instance);
7310
+
if (speechButton) {
7311
+
speechButton.disabled = true;
7312
+
}
7313
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.conversation_ended + '</div>');
7314
+
aiomaticRmLoading(chatbut, instance);
7315
+
return;
7316
+
}
7317
+
if(result.scope == 'user_message')
7318
+
{
7319
+
hasFinishReason = true;
7320
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
7321
+
appendx = processKatexMarkdown(appendx);
7322
+
}
7323
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
7324
+
appendx = aiomatic_parseMarkdown(appendx);
7325
+
}
7326
+
jQuery('#aiomatic_chat_history' + instance).html(initialContent + appendx);
7327
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
7328
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
7329
+
renderMathInElement(katexContainer, {
7330
+
delimiters: [
7331
+
7332
+
{ left: '\\(', right: '\\)', display: false },
7333
+
{ left: '\\[', right: '\\]', display: true }
7334
+
],
7335
+
throwOnError: false
7336
+
});
7337
+
}
7338
+
if (typeof eventGenerator !== 'undefined')
7339
+
{
7340
+
eventGenerator.close();
7341
+
jQuery('#aistopbut' + instance).hide();
7342
+
}
7343
+
aiomaticRmLoading(chatbut, instance);
7344
+
aiomatic_generator_working = false;
7345
+
}
7346
+
else
7347
+
{
7348
+
console.log('Unknown scope returned: ' + result);
7349
+
hasFinishReason = true;
7350
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
7351
+
aiomaticRmLoading(chatbut, instance);
7352
+
aiomatic_generator_working = false;
7353
+
if (typeof eventGenerator !== 'undefined')
7354
+
{
7355
+
eventGenerator.close();
7356
+
jQuery('#aistopbut' + instance).hide();
7357
+
}
7358
+
return;
7359
+
}
7360
+
}
7361
+
}
7362
+
},
7363
+
error: function(error) {
7364
+
console.log('Error while calling AI functions: ' + error.responseText);
7365
+
hasFinishReason = true;
7366
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
7367
+
aiomaticRmLoading(chatbut, instance);
7368
+
aiomatic_generator_working = false;
7369
+
if (typeof eventGenerator !== 'undefined')
7370
+
{
7371
+
eventGenerator.close();
7372
+
jQuery('#aistopbut' + instance).hide();
7373
+
}
7374
+
return;
7375
+
},
7376
+
});
7377
+
}
7378
+
}
7379
+
function threadRunCompletedEventHandler(e) {
7380
+
//console.log('Run completed:', data);
7381
+
eventGenerator.close();
7382
+
jQuery('#aistopbut' + instance).hide();
7383
+
var x_input_text = jQuery('#aiomatic_chat_history' + instance).html();
7384
+
if((persistent != 'off' && persistent != '0' && persistent != '') && user_id != '0' && error_generated == '')
7385
+
{
7386
+
var save_persistent = x_input_text;
7387
+
if(persistent == 'vector')
7388
+
{
7389
+
save_persistent = user_question;
7390
+
}
7391
+
var saving_index = '';
7392
+
var main_index = '';
7393
+
if(persistent == 'history')
7394
+
{
7395
+
saving_index = jQuery('#chat-log-identifier' + instance).val();
7396
+
main_index = jQuery('#chat-main-identifier' + instance).val();
7397
+
}
7398
+
jQuery.ajax({
7399
+
type: 'POST',
7400
+
url: aiomatic_chat_ajax_object.ajax_url,
7401
+
data: {
7402
+
action: 'aiomatic_user_meta_save',
7403
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
7404
+
persistent: persistent,
7405
+
thread_id: aiomatic_chat_ajax_object.thread_id,
7406
+
x_input_text: save_persistent,
7407
+
user_id: user_id,
7408
+
saving_index: saving_index,
7409
+
main_index: main_index
7410
+
},
7411
+
success: function(result) {
7412
+
if(result.name && result.msg)
7413
+
{
7414
+
var logsdrop = jQuery('#chat-logs-dropdown' + instance);
7415
+
if(logsdrop)
7416
+
{
7417
+
var newChatLogItem = jQuery('<div class="chat-log-item" id="chat-log-item' + saving_index + '" data-id="' + saving_index + '" onclick="aiomatic_trigger_chat_logs(\'' + saving_index + '\', \'' + instance + '\')">' + result.name + '<span onclick="aiomatic_remove_chat_logs(event, \'' + saving_index + '\', \'' + instance + '\');" class="aiomatic-remove-item">X</span></div>');
7418
+
var chatLogNew = logsdrop.find('.chat-log-new');
7419
+
if (chatLogNew.length)
7420
+
{
7421
+
var nextSibling = chatLogNew.next();
7422
+
if (nextSibling.length && nextSibling.hasClass('date-group-label'))
7423
+
{
7424
+
newChatLogItem.insertAfter(nextSibling);
7425
+
}
7426
+
else
7427
+
{
7428
+
newChatLogItem.insertAfter(chatLogNew);
7429
+
}
7430
+
}
7431
+
else
7432
+
{
7433
+
logsdrop.append(newChatLogItem);
7434
+
}
7435
+
}
7436
+
}
7437
+
},
7438
+
error: function(error) {
7439
+
console.log('Error while saving persistent user log: ' + error.responseText);
7440
+
},
7441
+
});
7442
+
}
7443
+
if(error_generated == '')
7444
+
{
7445
+
jQuery.ajax({
7446
+
type: 'POST',
7447
+
url: aiomatic_chat_ajax_object.ajax_url,
7448
+
data: {
7449
+
action: 'aiomatic_record_user_usage',
7450
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
7451
+
user_id: user_id,
7452
+
input_text: input_text,
7453
+
response_text: response_data,
7454
+
model: model,
7455
+
temp: temp,
7456
+
vision_file: vision_file,
7457
+
user_token_cap_per_day: aiomatic_chat_ajax_object.user_token_cap_per_day,
7458
+
source: 'chat'
7459
+
},
7460
+
success: function()
7461
+
{
7462
+
},
7463
+
error: function(error) {
7464
+
console.log('Error while saving user data: ' + error.responseText);
7465
+
},
7466
+
});
7467
+
}
7468
+
if(error_generated == '')
7469
+
{
7470
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7471
+
}
7472
+
var has_speech = false;
7473
+
if(aiomatic_chat_ajax_object.receive_message_sound != '')
7474
+
{
7475
+
var snd = new Audio(aiomatic_chat_ajax_object.receive_message_sound);
7476
+
snd.play();
7477
+
}
7478
+
if(error_generated == '' && !jQuery('.aiomatic-gg-unmute').length)
7479
+
{
7480
+
if(aiomatic_chat_ajax_object.text_speech == 'elevenlabs')
7481
+
{
7482
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
7483
+
response_data = aiomatic_stripHtmlTags(response_data);
7484
+
if(response_data != '')
7485
+
{
7486
+
has_speech = true;
7487
+
let speechData = new FormData();
7488
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
7489
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
7490
+
speechData.append('x_input_text', response_data);
7491
+
speechData.append('action', 'aiomatic_get_elevenlabs_voice_chat');
7492
+
var speechRequest = new XMLHttpRequest();
7493
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
7494
+
speechRequest.responseType = "arraybuffer";
7495
+
speechRequest.ontimeout = () => {
7496
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
7497
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7498
+
aiomaticRmLoading(chatbut, instance);
7499
+
aiomatic_generator_working = false;
7500
+
};
7501
+
speechRequest.onerror = function ()
7502
+
{
7503
+
console.error("Network Error");
7504
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7505
+
aiomaticRmLoading(chatbut, instance);
7506
+
aiomatic_generator_working = false;
7507
+
};
7508
+
speechRequest.onabort = function ()
7509
+
{
7510
+
console.error("The request was aborted.");
7511
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7512
+
aiomaticRmLoading(chatbut, instance);
7513
+
aiomatic_generator_working = false;
7514
+
};
7515
+
speechRequest.onload = function () {
7516
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
7517
+
var fr = new FileReader();
7518
+
fr.onload = function () {
7519
+
var fileText = this.result;
7520
+
try {
7521
+
try
7522
+
{
7523
+
var errorMessage = JSON.parse(fileText);
7524
+
console.log('ElevenLabs API failed: ' + errorMessage.msg);
7525
+
}
7526
+
catch (error) {
7527
+
console.error('Stream onload Error:', error);
7528
+
}
7529
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7530
+
aiomaticRmLoading(chatbut, instance);
7531
+
aiomatic_generator_working = false;
7532
+
} catch (errorBlob) {
7533
+
var blobUrl = URL.createObjectURL(blob);
7534
+
var audioElement = document.createElement('audio');
7535
+
audioElement.src = blobUrl;
7536
+
audioElement.controls = true;
7537
+
audioElement.style.marginTop = "2px";
7538
+
audioElement.style.width = "100%";
7539
+
audioElement.id = 'audio-element-' + instance;
7540
+
audioElement.addEventListener("error", function(event) {
7541
+
console.error("Error loading or playing the audio: ", event);
7542
+
});
7543
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
7544
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
7545
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
7546
+
{
7547
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
7548
+
var waveform = WaveSurfer.create({
7549
+
container: '#waveform-container' + instance,
7550
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
7551
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
7552
+
backend: 'MediaElement',
7553
+
height: 60,
7554
+
barWidth: 2,
7555
+
responsive: true, mediaControls: false, interact: false
7556
+
});
7557
+
waveform.setMuted(true);
7558
+
waveform.load(blobUrl);
7559
+
waveform.on('ready', function () {
7560
+
waveform.play();
7561
+
});
7562
+
audioElement.addEventListener('play', function () {
7563
+
waveform.play();
7564
+
});
7565
+
audioElement.addEventListener('pause', function () {
7566
+
waveform.pause();
7567
+
});
7568
+
}
7569
+
else
7570
+
{
7571
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7572
+
}
7573
+
audioElement.play();
7574
+
aiomaticRmLoading(chatbut, instance);
7575
+
aiomatic_generator_working = false;
7576
+
}
7577
+
}
7578
+
fr.readAsText(blob);
7579
+
}
7580
+
speechRequest.send(speechData);
7581
+
}
7582
+
}
7583
+
else
7584
+
{
7585
+
if(aiomatic_chat_ajax_object.text_speech == 'openai')
7586
+
{
7587
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
7588
+
response_data = aiomatic_stripHtmlTags(response_data);
7589
+
if(response_data != '')
7590
+
{
7591
+
has_speech = true;
7592
+
let speechData = new FormData();
7593
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
7594
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
7595
+
speechData.append('x_input_text', response_data);
7596
+
speechData.append('action', 'aiomatic_get_openai_voice_chat');
7597
+
var speechRequest = new XMLHttpRequest();
7598
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
7599
+
speechRequest.responseType = "arraybuffer";
7600
+
speechRequest.ontimeout = () => {
7601
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
7602
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7603
+
aiomaticRmLoading(chatbut, instance);
7604
+
aiomatic_generator_working = false;
7605
+
};
7606
+
speechRequest.onerror = function ()
7607
+
{
7608
+
console.error("Network Error");
7609
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7610
+
aiomaticRmLoading(chatbut, instance);
7611
+
aiomatic_generator_working = false;
7612
+
};
7613
+
speechRequest.onabort = function ()
7614
+
{
7615
+
console.error("The request was aborted.");
7616
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7617
+
aiomaticRmLoading(chatbut, instance);
7618
+
aiomatic_generator_working = false;
7619
+
};
7620
+
speechRequest.onload = function () {
7621
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
7622
+
var fr = new FileReader();
7623
+
fr.onload = function () {
7624
+
var fileText = this.result;
7625
+
try {
7626
+
try
7627
+
{
7628
+
var errorMessage = JSON.parse(fileText);
7629
+
console.log('OpenAI TTS API failed: ' + errorMessage.msg);
7630
+
}
7631
+
catch (error) {
7632
+
console.error('Stream onload new Error:', error);
7633
+
}
7634
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7635
+
aiomaticRmLoading(chatbut, instance);
7636
+
aiomatic_generator_working = false;
7637
+
} catch (errorBlob) {
7638
+
var blobUrl = URL.createObjectURL(blob);
7639
+
var audioElement = document.createElement('audio');
7640
+
audioElement.src = blobUrl;
7641
+
audioElement.controls = true;
7642
+
audioElement.style.marginTop = "2px";
7643
+
audioElement.style.width = "100%";
7644
+
audioElement.id = 'audio-element-' + instance;
7645
+
audioElement.addEventListener("error", function(event) {
7646
+
console.error("Error loading or playing the audio: ", event);
7647
+
});
7648
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
7649
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
7650
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
7651
+
{
7652
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
7653
+
var waveform = WaveSurfer.create({
7654
+
container: '#waveform-container' + instance,
7655
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
7656
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
7657
+
backend: 'MediaElement',
7658
+
height: 60,
7659
+
barWidth: 2,
7660
+
responsive: true, mediaControls: false, interact: false
7661
+
});
7662
+
waveform.setMuted(true);
7663
+
waveform.load(blobUrl);
7664
+
waveform.on('ready', function () {
7665
+
waveform.play();
7666
+
});
7667
+
audioElement.addEventListener('play', function () {
7668
+
waveform.play();
7669
+
});
7670
+
audioElement.addEventListener('pause', function () {
7671
+
waveform.pause();
7672
+
});
7673
+
}
7674
+
else
7675
+
{
7676
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7677
+
}
7678
+
audioElement.play();
7679
+
aiomaticRmLoading(chatbut, instance);
7680
+
aiomatic_generator_working = false;
7681
+
}
7682
+
}
7683
+
fr.readAsText(blob);
7684
+
}
7685
+
speechRequest.send(speechData);
7686
+
}
7687
+
}
7688
+
else
7689
+
{
7690
+
if(aiomatic_chat_ajax_object.text_speech == 'google')
7691
+
{
7692
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
7693
+
response_data = aiomatic_stripHtmlTags(response_data);
7694
+
if(response_data != '')
7695
+
{
7696
+
has_speech = true;
7697
+
let speechData = new FormData();
7698
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
7699
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
7700
+
speechData.append('x_input_text', response_data);
7701
+
speechData.append('action', 'aiomatic_get_google_voice_chat');
7702
+
var speechRequest = new XMLHttpRequest();
7703
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
7704
+
speechRequest.ontimeout = () => {
7705
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
7706
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7707
+
aiomaticRmLoading(chatbut, instance);
7708
+
aiomatic_generator_working = false;
7709
+
};
7710
+
speechRequest.onerror = function ()
7711
+
{
7712
+
console.error("Network Error");
7713
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7714
+
aiomaticRmLoading(chatbut, instance);
7715
+
aiomatic_generator_working = false;
7716
+
};
7717
+
speechRequest.onabort = function ()
7718
+
{
7719
+
console.error("The request was aborted.");
7720
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7721
+
aiomaticRmLoading(chatbut, instance);
7722
+
aiomatic_generator_working = false;
7723
+
};
7724
+
speechRequest.onload = function () {
7725
+
var result = speechRequest.responseText;
7726
+
try {
7727
+
try
7728
+
{
7729
+
var jsonresult = JSON.parse(result);
7730
+
if(jsonresult.status === 'success'){
7731
+
var byteCharacters = atob(jsonresult.audio);
7732
+
const byteNumbers = new Array(byteCharacters.length);
7733
+
for (let i = 0; i < byteCharacters.length; i++) {
7734
+
byteNumbers[i] = byteCharacters.charCodeAt(i);
7735
+
}
7736
+
const byteArray = new Uint8Array(byteNumbers);
7737
+
const blob = new Blob([byteArray], {type: 'audio/mp3'});
7738
+
var blobUrl = URL.createObjectURL(blob);
7739
+
var audioElement = document.createElement('audio');
7740
+
audioElement.src = blobUrl;
7741
+
audioElement.controls = true;
7742
+
audioElement.style.marginTop = "2px";
7743
+
audioElement.style.width = "100%";
7744
+
audioElement.id = 'audio-element-' + instance;
7745
+
audioElement.addEventListener("error", function(event) {
7746
+
console.error("Error loading or playing the audio: ", event);
7747
+
});
7748
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
7749
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
7750
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
7751
+
{
7752
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
7753
+
var waveform = WaveSurfer.create({
7754
+
container: '#waveform-container' + instance,
7755
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
7756
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
7757
+
backend: 'MediaElement',
7758
+
height: 60,
7759
+
barWidth: 2,
7760
+
responsive: true, mediaControls: false, interact: false
7761
+
});
7762
+
waveform.setMuted(true);
7763
+
waveform.load(blobUrl);
7764
+
waveform.on('ready', function () {
7765
+
waveform.play();
7766
+
});
7767
+
audioElement.addEventListener('play', function () {
7768
+
waveform.play();
7769
+
});
7770
+
audioElement.addEventListener('pause', function () {
7771
+
waveform.pause();
7772
+
});
7773
+
}
7774
+
else
7775
+
{
7776
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7777
+
}
7778
+
audioElement.play();
7779
+
aiomaticRmLoading(chatbut, instance);
7780
+
aiomatic_generator_working = false;
7781
+
}
7782
+
else{
7783
+
var errorMessageDetail = 'Google: ' + jsonresult.msg;
7784
+
console.log('Google Text-to-Speech error: ' + errorMessageDetail);
7785
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7786
+
aiomaticRmLoading(chatbut, instance);
7787
+
aiomatic_generator_working = false;
7788
+
}
7789
+
}
7790
+
catch (error) {
7791
+
console.error('Jsontext decode:', error);
7792
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7793
+
aiomaticRmLoading(chatbut, instance);
7794
+
aiomatic_generator_working = false;
7795
+
}
7796
+
}
7797
+
catch (errorSpeech){
7798
+
console.log('Exception in Google Text-to-Speech API: ' + errorSpeech);
7799
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7800
+
aiomaticRmLoading(chatbut, instance);
7801
+
aiomatic_generator_working = false;
7802
+
}
7803
+
}
7804
+
speechRequest.send(speechData);
7805
+
}
7806
+
}
7807
+
else
7808
+
{
7809
+
if(aiomatic_chat_ajax_object.text_speech == 'did')
7810
+
{
7811
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
7812
+
response_data = aiomatic_stripHtmlTags(response_data);
7813
+
if(response_data != '')
7814
+
{
7815
+
has_speech = true;
7816
+
let speechData = new FormData();
7817
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
7818
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
7819
+
speechData.append('x_input_text', response_data);
7820
+
speechData.append('action', 'aiomatic_get_d_id_video_chat');
7821
+
var speechRequest = new XMLHttpRequest();
7822
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
7823
+
speechRequest.ontimeout = () => {
7824
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
7825
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7826
+
aiomaticRmLoading(chatbut, instance);
7827
+
aiomatic_generator_working = false;
7828
+
};
7829
+
speechRequest.onerror = function ()
7830
+
{
7831
+
console.error("Network Error");
7832
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7833
+
aiomaticRmLoading(chatbut, instance);
7834
+
aiomatic_generator_working = false;
7835
+
};
7836
+
speechRequest.onabort = function ()
7837
+
{
7838
+
console.error("The request was aborted.");
7839
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7840
+
aiomaticRmLoading(chatbut, instance);
7841
+
aiomatic_generator_working = false;
7842
+
};
7843
+
speechRequest.onload = function () {
7844
+
var result = speechRequest.responseText;
7845
+
try
7846
+
{
7847
+
var jsonresult = JSON.parse(result);
7848
+
if(jsonresult.status === 'success')
7849
+
{
7850
+
var videoURL = '<video class="ai_video" autoplay="autoplay" controls="controls"><source src="' + jsonresult.video + '" type="video/mp4"></video>';
7851
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-video">' + videoURL + '</div>');
7852
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7853
+
aiomaticRmLoading(chatbut, instance);
7854
+
aiomatic_generator_working = false;
7855
+
}
7856
+
else
7857
+
{
7858
+
var errorMessageDetail = 'D-ID: ' + jsonresult.msg;
7859
+
console.log('D-ID Text-to-video error: ' + errorMessageDetail);
7860
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7861
+
aiomaticRmLoading(chatbut, instance);
7862
+
aiomatic_generator_working = false;
7863
+
}
7864
+
}
7865
+
catch (errorSpeech){
7866
+
console.log('Exception in D-ID Text-to-video API: ' + errorSpeech);
7867
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7868
+
aiomaticRmLoading(chatbut, instance);
7869
+
aiomatic_generator_working = false;
7870
+
}
7871
+
}
7872
+
speechRequest.send(speechData);
7873
+
}
7874
+
}
7875
+
else
7876
+
{
7877
+
if(aiomatic_chat_ajax_object.text_speech == 'didstream')
7878
+
{
7879
+
if(avatarImageUrl != '' && did_app_id != '')
7880
+
{
7881
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
7882
+
response_data = aiomatic_stripHtmlTags(response_data);
7883
+
if(response_data != '')
7884
+
{
7885
+
if(streamingEpicFail === false)
7886
+
{
7887
+
has_speech = true;
7888
+
myStreamObject.talkToDidStream(response_data);
7889
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7890
+
aiomatic_generator_working = false;
7891
+
}
7892
+
}
7893
+
}
7894
+
}
7895
+
else
7896
+
{
7897
+
if(aiomatic_chat_ajax_object.text_speech == 'azure')
7898
+
{
7899
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
7900
+
response_data = aiomatic_stripHtmlTags(response_data);
7901
+
if(response_data != '')
7902
+
{
7903
+
if(azure_speech_id != '')
7904
+
{
7905
+
if(streamingEpicFail === false)
7906
+
{
7907
+
has_speech = true;
7908
+
var ttsvoice = aiomatic_chat_ajax_object.azure_voice;
7909
+
var personalVoiceSpeakerProfileID = aiomatic_chat_ajax_object.azure_voice_profile;
7910
+
aiomaticRmLoading(chatbut, instance);
7911
+
azureSpeakText(response_data, ttsvoice, personalVoiceSpeakerProfileID);
7912
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7913
+
aiomatic_generator_working = false;
7914
+
}
7915
+
}
7916
+
}
7917
+
}
7918
+
else
7919
+
{
7920
+
if(aiomatic_chat_ajax_object.text_speech == 'free')
7921
+
{
7922
+
var T2S;
7923
+
if("speechSynthesis" in window || speechSynthesis)
7924
+
{
7925
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
7926
+
response_data = aiomatic_stripHtmlTags(response_data);
7927
+
if(response_data != '')
7928
+
{
7929
+
T2S = window.speechSynthesis || speechSynthesis;
7930
+
var utter = new SpeechSynthesisUtterance(response_data);
7931
+
var voiceSetting = aiomatic_chat_ajax_object.free_voice.split(";");
7932
+
var desiredVoiceName = voiceSetting[0].trim();
7933
+
var desiredLang = voiceSetting[1].trim();
7934
+
var voices = T2S.getVoices();
7935
+
var selectedVoice = voices.find(function(voice) {
7936
+
return voice.name === desiredVoiceName && voice.lang === desiredLang;
7937
+
});
7938
+
if (selectedVoice) {
7939
+
utter.voice = selectedVoice;
7940
+
utter.lang = selectedVoice.lang;
7941
+
}
7942
+
else
7943
+
{
7944
+
utter.lang = desiredLang;
7945
+
}
7946
+
T2S.speak(utter);
7947
+
}
7948
+
}
7949
+
}
7950
+
}
7951
+
}
7952
+
}
7953
+
}
7954
+
}
7955
+
}
7956
+
}
7957
+
if(has_speech === false)
7958
+
{
7959
+
if(error_generated == '')
7960
+
{
7961
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
7962
+
}
7963
+
aiomaticRmLoading(chatbut, instance);
7964
+
aiomatic_generator_working = false;
7965
+
}
7966
+
}
7967
+
function threadRunCancellingEventHandler(e) {
7968
+
//console.log('Run cancelling:', data);
7969
+
}
7970
+
function threadRunCancelledEventHandler(e) {
7971
+
//console.log('Run cancelled:', data);
7972
+
}
7973
+
function threadRunExpiredEventHandler(e) {
7974
+
//console.log('Run expired:', data);
7975
+
}
7976
+
function threadRunStepCreatedEventHandler(e) {
7977
+
//console.log('Run step created:', data);
7978
+
}
7979
+
function threadRunStepInProgressEventHandler(e) {
7980
+
//console.log('Run step in progress:', data);
7981
+
}
7982
+
function threadRunStepDeltaEventHandler(e) {
7983
+
try
7984
+
{
7985
+
var data = JSON.parse(e.data);
7986
+
//console.log('Run step delta:', data);
7987
+
var xarr = {'tool_calls': []};
7988
+
xarr.tool_calls.push(data.delta.step_details.tool_calls[0]);
7989
+
aiomatic_mergeDeep(func_call, xarr);
7990
+
func_calls++;
7991
+
}
7992
+
catch (error) {
7993
+
console.error('Func call Error:', error);
7994
+
}
7995
+
}
7996
+
function threadRunStepCompletedEventHandler(e) {
7997
+
//console.log('Run step completed:', data);
7998
+
}
7999
+
function threadRunStepCancelledEventHandler(e) {
8000
+
//console.log('Run step cancelled:', data);
8001
+
}
8002
+
function threadRunStepExpiredEventHandler(e) {
8003
+
//console.log('Run step expired:', data);
8004
+
}
8005
+
function threadMessageCreatedEventHandler(e) {
8006
+
//console.log('Run message created:', data);
8007
+
}
8008
+
function threadMessageInProgressEventHandler(e) {
8009
+
//console.log('Run message in progress:', data);
8010
+
}
8011
+
function threadMessageDeltaEventHandler(e) {
8012
+
try
8013
+
{
8014
+
var data = JSON.parse(e.data);
8015
+
if(typeof data.delta.content[0].text.value !== 'undefined')
8016
+
{
8017
+
content_generated = data.delta.content[0].text.value;
8018
+
if(aiomatic_chat_ajax_object.enable_html != true)
8019
+
{
8020
+
content_generated = aiomatic_esc_html(content_generated);
8021
+
}
8022
+
response_data += aiomatic_nl2br(content_generated);
8023
+
if(aiomatic_chat_ajax_object.strip_js == true)
8024
+
{
8025
+
response_data = response_data.replace(/<script[\s\S]*?<\/script>/gi, '');
8026
+
response_data = response_data.replace(/on\w+="[^"]*"/gi, '');
8027
+
}
8028
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
8029
+
response_data = processKatexMarkdown(response_data);
8030
+
}
8031
+
if(aiomatic_chat_ajax_object.markdown_parse == 'on')
8032
+
{
8033
+
response_data = aiomatic_parseMarkdown(response_data);
8034
+
}
8035
+
var appendx = '<div class="ai-wrapper">';
8036
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
8037
+
{
8038
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
8039
+
}
8040
+
appendx += '<div class="ai-bubble ai-other">' + response_data + '</div>';
8041
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
8042
+
{
8043
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
8044
+
}
8045
+
appendx += '</div>';
8046
+
jQuery('#aiomatic_chat_history' + instance).html(initialContent + appendx);
8047
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
8048
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
8049
+
renderMathInElement(katexContainer, {
8050
+
delimiters: [
8051
+
8052
+
{ left: '\\(', right: '\\)', display: false },
8053
+
{ left: '\\[', right: '\\]', display: true }
8054
+
],
8055
+
throwOnError: false
8056
+
});
8057
+
}
8058
+
}
8059
+
else
8060
+
{
8061
+
console.log('Generated content not found: ' + data);
8062
+
}
8063
+
}
8064
+
catch (error) {
8065
+
console.error('Delta handler Error:', error);
8066
+
}
8067
+
}
8068
+
function threadMessageIncompleteEventHandler(e) {
8069
+
//console.log('Run message incomplete:', data);
8070
+
eventGenerator.close();
8071
+
jQuery('#aistopbut' + instance).hide();
8072
+
}
8073
+
function threadRunFailedEventHandler(e) {
8074
+
//console.log('Run failed:', data);
8075
+
console.warn(e);
8076
+
aiomaticRmLoading(chatbut, instance);
8077
+
aiomatic_generator_working = false;
8078
+
eventGenerator.close();
8079
+
jQuery('#aistopbut' + instance).hide();
8080
+
return;
8081
+
}
8082
+
function threadRunStepFailedEventHandler(e) {
8083
+
//console.log('Run step failed:', data);
8084
+
console.warn(e);
8085
+
aiomaticRmLoading(chatbut, instance);
8086
+
aiomatic_generator_working = false;
8087
+
eventGenerator.close();
8088
+
jQuery('#aistopbut' + instance).hide();
8089
+
return;
8090
+
}
8091
+
function threadMessageCompletedEventHandler(e) {
8092
+
//console.log('Run message completed:', data);
8093
+
}
8094
+
function handleCompletionEvent(e)
8095
+
{
8096
+
if(aiomatic_chat_ajax_object.model_type == 'claude')
8097
+
{
8098
+
var aiomatic_newline_before = false;
8099
+
var aiomatic_response_events = 0;
8100
+
var aiomatic_limitLines = 1;
8101
+
var currentContent = jQuery('#aiomatic_chat_history' + instance).html();
8102
+
var resultData = null;
8103
+
if(e.data == '[DONE]')
8104
+
{
8105
+
var hasFinishReason = true;
8106
+
}
8107
+
else
8108
+
{
8109
+
try
8110
+
{
8111
+
resultData = JSON.parse(e.data);
8112
+
}
8113
+
catch (e)
8114
+
{
8115
+
console.warn(e);
8116
+
aiomaticRmLoading(chatbut, instance);
8117
+
aiomatic_generator_working = false;
8118
+
eventGenerator.close();
8119
+
jQuery('#aistopbut' + instance).hide();
8120
+
return;
8121
+
}
8122
+
var hasFinishReason = resultData &&
8123
+
(resultData.finish_reason === "stop" ||
8124
+
resultData.finish_reason === "length");
8125
+
if(resultData.stop_reason == 'stop_sequence' || resultData.stop_reason == 'max_tokens')
8126
+
{
8127
+
hasFinishReason = true;
8128
+
}
8129
+
}
8130
+
var content_generated = '';
8131
+
if(hasFinishReason){
8132
+
count_line += 1;
8133
+
aiomatic_response_events = 0;
8134
+
}
8135
+
else
8136
+
{
8137
+
if(resultData !== null)
8138
+
{
8139
+
var result = resultData;
8140
+
}
8141
+
else
8142
+
{
8143
+
var result = null;
8144
+
try {
8145
+
result = JSON.parse(e.data);
8146
+
}
8147
+
catch (e)
8148
+
{
8149
+
console.warn(e);
8150
+
aiomaticRmLoading(chatbut, instance);
8151
+
aiomatic_generator_working = false;
8152
+
eventGenerator.close();
8153
+
jQuery('#aistopbut' + instance).hide();
8154
+
return;
8155
+
};
8156
+
}
8157
+
if(result.error !== undefined){
8158
+
if(result.error !== undefined){
8159
+
error_generated = result.error[0].message;
8160
+
}
8161
+
else
8162
+
{
8163
+
error_generated = JSON.stringify(result.error);
8164
+
}
8165
+
if(error_generated === undefined)
8166
+
{
8167
+
error_generated = result.error.message;
8168
+
}
8169
+
if(error_generated === undefined)
8170
+
{
8171
+
error_generated = result.error;
8172
+
}
8173
+
console.log('Error while processing request(1b): ' + error_generated);
8174
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + error_generated + '</div>');
8175
+
}
8176
+
else
8177
+
{
8178
+
if(result.completion !== undefined)
8179
+
{
8180
+
content_generated = result.completion;
8181
+
}
8182
+
else if(result.content[0].text !== undefined)
8183
+
{
8184
+
content_generated = result.content[0].text;
8185
+
}
8186
+
else
8187
+
{
8188
+
content_generated = '';
8189
+
}
8190
+
}
8191
+
if(aiomatic_chat_ajax_object.enable_html != true)
8192
+
{
8193
+
content_generated = aiomatic_esc_html(content_generated);
8194
+
}
8195
+
response_data += aiomatic_nl2br(content_generated);
8196
+
if(aiomatic_chat_ajax_object.strip_js == true)
8197
+
{
8198
+
response_data = response_data.replace(/<script[\s\S]*?<\/script>/gi, '');
8199
+
response_data = response_data.replace(/on\w+="[^"]*"/gi, '');
8200
+
}
8201
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
8202
+
response_data = processKatexMarkdown(response_data);
8203
+
}
8204
+
if(aiomatic_chat_ajax_object.markdown_parse == 'on')
8205
+
{
8206
+
response_data = aiomatic_parseMarkdown(response_data);
8207
+
}
8208
+
var appendx = '<div class="ai-wrapper">';
8209
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
8210
+
{
8211
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
8212
+
}
8213
+
appendx += '<div class="ai-bubble ai-other">' + response_data + '</div>';
8214
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
8215
+
{
8216
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
8217
+
}
8218
+
appendx += '</div>';
8219
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
8220
+
appendx = processKatexMarkdown(appendx);
8221
+
}
8222
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
8223
+
appendx = aiomatic_parseMarkdown(appendx);
8224
+
}
8225
+
if((content_generated === '\n' || content_generated === ' \n' || content_generated === '.\n' || content_generated === '\n\n' || content_generated === '.\n\n' || content_generated === '"\n') && aiomatic_response_events > 0 && currentContent !== ''){
8226
+
if(!aiomatic_newline_before) {
8227
+
aiomatic_newline_before = true;
8228
+
jQuery('#aiomatic_chat_history' + instance).html(currentContent + '<br /><br />');
8229
+
}
8230
+
}
8231
+
else if(content_generated === '\n' && aiomatic_response_events === 0 && currentContent === ''){
8232
+
8233
+
}
8234
+
else{
8235
+
aiomatic_newline_before = false;
8236
+
aiomatic_response_events += 1;
8237
+
jQuery('#aiomatic_chat_history' + instance).html(initialContent + appendx);
8238
+
}
8239
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
8240
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
8241
+
renderMathInElement(katexContainer, {
8242
+
delimiters: [
8243
+
8244
+
{ left: '\\(', right: '\\)', display: false },
8245
+
{ left: '\\[', right: '\\]', display: true }
8246
+
],
8247
+
throwOnError: false
8248
+
});
8249
+
}
8250
+
}
8251
+
if(count_line >= aiomatic_limitLines)
8252
+
{
8253
+
eventGenerator.close();
8254
+
jQuery('#aistopbut' + instance).hide();
8255
+
var x_input_text = jQuery('#aiomatic_chat_history' + instance).html();
8256
+
if((persistent != 'off' && persistent != '0' && persistent != '') && user_id != '0' && error_generated == '')
8257
+
{
8258
+
var save_persistent = x_input_text;
8259
+
if(persistent == 'vector')
8260
+
{
8261
+
save_persistent = user_question;
8262
+
}
8263
+
var saving_index = '';
8264
+
var main_index = '';
8265
+
if(persistent == 'history')
8266
+
{
8267
+
saving_index = jQuery('#chat-log-identifier' + instance).val();
8268
+
main_index = jQuery('#chat-main-identifier' + instance).val();
8269
+
}
8270
+
jQuery.ajax({
8271
+
type: 'POST',
8272
+
url: aiomatic_chat_ajax_object.ajax_url,
8273
+
data: {
8274
+
action: 'aiomatic_user_meta_save',
8275
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
8276
+
persistent: persistent,
8277
+
thread_id: aiomatic_chat_ajax_object.thread_id,
8278
+
x_input_text: save_persistent,
8279
+
user_id: user_id,
8280
+
saving_index: saving_index,
8281
+
main_index: main_index
8282
+
},
8283
+
success: function(result) {
8284
+
if(result.name && result.msg)
8285
+
{
8286
+
var logsdrop = jQuery('#chat-logs-dropdown' + instance);
8287
+
if(logsdrop)
8288
+
{
8289
+
var newChatLogItem = jQuery('<div class="chat-log-item" id="chat-log-item' + saving_index + '" data-id="' + saving_index + '" onclick="aiomatic_trigger_chat_logs(\'' + saving_index + '\', \'' + instance + '\')">' + result.name + '<span onclick="aiomatic_remove_chat_logs(event, \'' + saving_index + '\', \'' + instance + '\');" class="aiomatic-remove-item">X</span></div>');
8290
+
var chatLogNew = logsdrop.find('.chat-log-new');
8291
+
if (chatLogNew.length)
8292
+
{
8293
+
var nextSibling = chatLogNew.next();
8294
+
if (nextSibling.length && nextSibling.hasClass('date-group-label'))
8295
+
{
8296
+
newChatLogItem.insertAfter(nextSibling);
8297
+
}
8298
+
else
8299
+
{
8300
+
newChatLogItem.insertAfter(chatLogNew);
8301
+
}
8302
+
}
8303
+
else
8304
+
{
8305
+
logsdrop.append(newChatLogItem);
8306
+
}
8307
+
}
8308
+
}
8309
+
},
8310
+
error: function(error) {
8311
+
console.log('Error while saving persistent user log: ' + error.responseText);
8312
+
},
8313
+
});
8314
+
}
8315
+
if(error_generated == '')
8316
+
{
8317
+
jQuery.ajax({
8318
+
type: 'POST',
8319
+
url: aiomatic_chat_ajax_object.ajax_url,
8320
+
data: {
8321
+
action: 'aiomatic_record_user_usage',
8322
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
8323
+
user_id: user_id,
8324
+
input_text: input_text,
8325
+
response_text: response_data,
8326
+
model: model,
8327
+
temp: temp,
8328
+
vision_file: vision_file,
8329
+
user_token_cap_per_day: aiomatic_chat_ajax_object.user_token_cap_per_day,
8330
+
source: 'chat'
8331
+
},
8332
+
success: function()
8333
+
{
8334
+
},
8335
+
error: function(error) {
8336
+
console.log('Error while saving user data: ' + error.responseText);
8337
+
},
8338
+
});
8339
+
}
8340
+
if(error_generated == '')
8341
+
{
8342
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8343
+
}
8344
+
var has_speech = false;
8345
+
if(aiomatic_chat_ajax_object.receive_message_sound != '')
8346
+
{
8347
+
var snd = new Audio(aiomatic_chat_ajax_object.receive_message_sound);
8348
+
snd.play();
8349
+
}
8350
+
if(error_generated == '' && !jQuery('.aiomatic-gg-unmute').length)
8351
+
{
8352
+
if(aiomatic_chat_ajax_object.text_speech == 'elevenlabs')
8353
+
{
8354
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
8355
+
response_data = aiomatic_stripHtmlTags(response_data);
8356
+
if(response_data != '')
8357
+
{
8358
+
has_speech = true;
8359
+
let speechData = new FormData();
8360
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
8361
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
8362
+
speechData.append('x_input_text', response_data);
8363
+
speechData.append('action', 'aiomatic_get_elevenlabs_voice_chat');
8364
+
var speechRequest = new XMLHttpRequest();
8365
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
8366
+
speechRequest.responseType = "arraybuffer";
8367
+
speechRequest.ontimeout = () => {
8368
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
8369
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8370
+
aiomaticRmLoading(chatbut, instance);
8371
+
aiomatic_generator_working = false;
8372
+
};
8373
+
speechRequest.onerror = function ()
8374
+
{
8375
+
console.error("Network Error");
8376
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8377
+
aiomaticRmLoading(chatbut, instance);
8378
+
aiomatic_generator_working = false;
8379
+
};
8380
+
speechRequest.onabort = function ()
8381
+
{
8382
+
console.error("The request was aborted.");
8383
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8384
+
aiomaticRmLoading(chatbut, instance);
8385
+
aiomatic_generator_working = false;
8386
+
};
8387
+
speechRequest.onload = function () {
8388
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
8389
+
var fr = new FileReader();
8390
+
fr.onload = function () {
8391
+
var fileText = this.result;
8392
+
try {
8393
+
var errorMessage = JSON.parse(fileText);
8394
+
console.log('ElevenLabs API failed: ' + errorMessage.msg);
8395
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8396
+
aiomaticRmLoading(chatbut, instance);
8397
+
aiomatic_generator_working = false;
8398
+
} catch (errorBlob) {
8399
+
var blobUrl = URL.createObjectURL(blob);
8400
+
var audioElement = document.createElement('audio');
8401
+
audioElement.src = blobUrl;
8402
+
audioElement.controls = true;
8403
+
audioElement.style.marginTop = "2px";
8404
+
audioElement.style.width = "100%";
8405
+
audioElement.id = 'audio-element-' + instance;
8406
+
audioElement.addEventListener("error", function(event) {
8407
+
console.error("Error loading or playing the audio: ", event);
8408
+
});
8409
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
8410
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
8411
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
8412
+
{
8413
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
8414
+
var waveform = WaveSurfer.create({
8415
+
container: '#waveform-container' + instance,
8416
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
8417
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
8418
+
backend: 'MediaElement',
8419
+
height: 60,
8420
+
barWidth: 2,
8421
+
responsive: true, mediaControls: false, interact: false
8422
+
});
8423
+
waveform.setMuted(true);
8424
+
waveform.load(blobUrl);
8425
+
waveform.on('ready', function () {
8426
+
waveform.play();
8427
+
});
8428
+
audioElement.addEventListener('play', function () {
8429
+
waveform.play();
8430
+
});
8431
+
audioElement.addEventListener('pause', function () {
8432
+
waveform.pause();
8433
+
});
8434
+
}
8435
+
else
8436
+
{
8437
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8438
+
}
8439
+
audioElement.play();
8440
+
aiomaticRmLoading(chatbut, instance);
8441
+
aiomatic_generator_working = false;
8442
+
}
8443
+
}
8444
+
fr.readAsText(blob);
8445
+
}
8446
+
speechRequest.send(speechData);
8447
+
}
8448
+
}
8449
+
else
8450
+
{
8451
+
if(aiomatic_chat_ajax_object.text_speech == 'openai')
8452
+
{
8453
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
8454
+
response_data = aiomatic_stripHtmlTags(response_data);
8455
+
if(response_data != '')
8456
+
{
8457
+
has_speech = true;
8458
+
let speechData = new FormData();
8459
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
8460
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
8461
+
speechData.append('x_input_text', response_data);
8462
+
speechData.append('action', 'aiomatic_get_openai_voice_chat');
8463
+
var speechRequest = new XMLHttpRequest();
8464
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
8465
+
speechRequest.responseType = "arraybuffer";
8466
+
speechRequest.ontimeout = () => {
8467
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
8468
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8469
+
aiomaticRmLoading(chatbut, instance);
8470
+
aiomatic_generator_working = false;
8471
+
};
8472
+
speechRequest.onerror = function ()
8473
+
{
8474
+
console.error("Network Error");
8475
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8476
+
aiomaticRmLoading(chatbut, instance);
8477
+
aiomatic_generator_working = false;
8478
+
};
8479
+
speechRequest.onabort = function ()
8480
+
{
8481
+
console.error("The request was aborted.");
8482
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8483
+
aiomaticRmLoading(chatbut, instance);
8484
+
aiomatic_generator_working = false;
8485
+
};
8486
+
speechRequest.onload = function () {
8487
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
8488
+
var fr = new FileReader();
8489
+
fr.onload = function () {
8490
+
var fileText = this.result;
8491
+
try {
8492
+
var errorMessage = JSON.parse(fileText);
8493
+
console.log('OpenAI TTS API failed: ' + errorMessage.msg);
8494
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8495
+
aiomaticRmLoading(chatbut, instance);
8496
+
aiomatic_generator_working = false;
8497
+
} catch (errorBlob) {
8498
+
var blobUrl = URL.createObjectURL(blob);
8499
+
var audioElement = document.createElement('audio');
8500
+
audioElement.src = blobUrl;
8501
+
audioElement.controls = true;
8502
+
audioElement.style.marginTop = "2px";
8503
+
audioElement.style.width = "100%";
8504
+
audioElement.id = 'audio-element-' + instance;
8505
+
audioElement.addEventListener("error", function(event) {
8506
+
console.error("Error loading or playing the audio: ", event);
8507
+
});
8508
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
8509
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
8510
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
8511
+
{
8512
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
8513
+
var waveform = WaveSurfer.create({
8514
+
container: '#waveform-container' + instance,
8515
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
8516
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
8517
+
backend: 'MediaElement',
8518
+
height: 60,
8519
+
barWidth: 2,
8520
+
responsive: true, mediaControls: false, interact: false
8521
+
});
8522
+
waveform.setMuted(true);
8523
+
waveform.load(blobUrl);
8524
+
waveform.on('ready', function () {
8525
+
waveform.play();
8526
+
});
8527
+
audioElement.addEventListener('play', function () {
8528
+
waveform.play();
8529
+
});
8530
+
audioElement.addEventListener('pause', function () {
8531
+
waveform.pause();
8532
+
});
8533
+
}
8534
+
else
8535
+
{
8536
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8537
+
}
8538
+
audioElement.play();
8539
+
aiomaticRmLoading(chatbut, instance);
8540
+
aiomatic_generator_working = false;
8541
+
}
8542
+
}
8543
+
fr.readAsText(blob);
8544
+
}
8545
+
speechRequest.send(speechData);
8546
+
}
8547
+
}
8548
+
else
8549
+
{
8550
+
if(aiomatic_chat_ajax_object.text_speech == 'google')
8551
+
{
8552
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
8553
+
response_data = aiomatic_stripHtmlTags(response_data);
8554
+
if(response_data != '')
8555
+
{
8556
+
has_speech = true;
8557
+
let speechData = new FormData();
8558
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
8559
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
8560
+
speechData.append('x_input_text', response_data);
8561
+
speechData.append('action', 'aiomatic_get_google_voice_chat');
8562
+
var speechRequest = new XMLHttpRequest();
8563
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
8564
+
speechRequest.ontimeout = () => {
8565
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
8566
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8567
+
aiomaticRmLoading(chatbut, instance);
8568
+
aiomatic_generator_working = false;
8569
+
};
8570
+
speechRequest.onerror = function ()
8571
+
{
8572
+
console.error("Network Error");
8573
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8574
+
aiomaticRmLoading(chatbut, instance);
8575
+
aiomatic_generator_working = false;
8576
+
};
8577
+
speechRequest.onabort = function ()
8578
+
{
8579
+
console.error("The request was aborted.");
8580
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8581
+
aiomaticRmLoading(chatbut, instance);
8582
+
aiomatic_generator_working = false;
8583
+
};
8584
+
speechRequest.onload = function () {
8585
+
var result = speechRequest.responseText;
8586
+
try {
8587
+
var jsonresult = JSON.parse(result);
8588
+
if(jsonresult.status === 'success'){
8589
+
var byteCharacters = atob(jsonresult.audio);
8590
+
const byteNumbers = new Array(byteCharacters.length);
8591
+
for (let i = 0; i < byteCharacters.length; i++) {
8592
+
byteNumbers[i] = byteCharacters.charCodeAt(i);
8593
+
}
8594
+
const byteArray = new Uint8Array(byteNumbers);
8595
+
const blob = new Blob([byteArray], {type: 'audio/mp3'});
8596
+
var blobUrl = URL.createObjectURL(blob);
8597
+
var audioElement = document.createElement('audio');
8598
+
audioElement.src = blobUrl;
8599
+
audioElement.controls = true;
8600
+
audioElement.style.marginTop = "2px";
8601
+
audioElement.style.width = "100%";
8602
+
audioElement.id = 'audio-element-' + instance;
8603
+
audioElement.addEventListener("error", function(event) {
8604
+
console.error("Error loading or playing the audio: ", event);
8605
+
});
8606
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
8607
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
8608
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
8609
+
{
8610
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
8611
+
var waveform = WaveSurfer.create({
8612
+
container: '#waveform-container' + instance,
8613
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
8614
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
8615
+
backend: 'MediaElement',
8616
+
height: 60,
8617
+
barWidth: 2,
8618
+
responsive: true, mediaControls: false, interact: false
8619
+
});
8620
+
waveform.setMuted(true);
8621
+
waveform.load(blobUrl);
8622
+
waveform.on('ready', function () {
8623
+
waveform.play();
8624
+
});
8625
+
audioElement.addEventListener('play', function () {
8626
+
waveform.play();
8627
+
});
8628
+
audioElement.addEventListener('pause', function () {
8629
+
waveform.pause();
8630
+
});
8631
+
}
8632
+
else
8633
+
{
8634
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8635
+
}
8636
+
audioElement.play();
8637
+
aiomaticRmLoading(chatbut, instance);
8638
+
aiomatic_generator_working = false;
8639
+
}
8640
+
else{
8641
+
var errorMessageDetail = 'Google: ' + jsonresult.msg;
8642
+
console.log('Google Text-to-Speech error: ' + errorMessageDetail);
8643
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8644
+
aiomaticRmLoading(chatbut, instance);
8645
+
aiomatic_generator_working = false;
8646
+
}
8647
+
}
8648
+
catch (errorSpeech){
8649
+
console.log('Exception in Google Text-to-Speech API: ' + errorSpeech);
8650
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8651
+
aiomaticRmLoading(chatbut, instance);
8652
+
aiomatic_generator_working = false;
8653
+
}
8654
+
}
8655
+
speechRequest.send(speechData);
8656
+
}
8657
+
}
8658
+
else
8659
+
{
8660
+
if(aiomatic_chat_ajax_object.text_speech == 'did')
8661
+
{
8662
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
8663
+
response_data = aiomatic_stripHtmlTags(response_data);
8664
+
if(response_data != '')
8665
+
{
8666
+
has_speech = true;
8667
+
let speechData = new FormData();
8668
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
8669
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
8670
+
speechData.append('x_input_text', response_data);
8671
+
speechData.append('action', 'aiomatic_get_d_id_video_chat');
8672
+
var speechRequest = new XMLHttpRequest();
8673
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
8674
+
speechRequest.ontimeout = () => {
8675
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
8676
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8677
+
aiomaticRmLoading(chatbut, instance);
8678
+
aiomatic_generator_working = false;
8679
+
};
8680
+
speechRequest.onerror = function ()
8681
+
{
8682
+
console.error("Network Error");
8683
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8684
+
aiomaticRmLoading(chatbut, instance);
8685
+
aiomatic_generator_working = false;
8686
+
};
8687
+
speechRequest.onabort = function ()
8688
+
{
8689
+
console.error("The request was aborted.");
8690
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8691
+
aiomaticRmLoading(chatbut, instance);
8692
+
aiomatic_generator_working = false;
8693
+
};
8694
+
speechRequest.onload = function () {
8695
+
var result = speechRequest.responseText;
8696
+
try
8697
+
{
8698
+
var jsonresult = JSON.parse(result);
8699
+
if(jsonresult.status === 'success')
8700
+
{
8701
+
var videoURL = '<video class="ai_video" autoplay="autoplay" controls="controls"><source src="' + jsonresult.video + '" type="video/mp4"></video>';
8702
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-video">' + videoURL + '</div>');
8703
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8704
+
aiomaticRmLoading(chatbut, instance);
8705
+
aiomatic_generator_working = false;
8706
+
}
8707
+
else
8708
+
{
8709
+
var errorMessageDetail = 'D-ID: ' + jsonresult.msg;
8710
+
console.log('D-ID Text-to-video error: ' + errorMessageDetail);
8711
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8712
+
aiomaticRmLoading(chatbut, instance);
8713
+
aiomatic_generator_working = false;
8714
+
}
8715
+
}
8716
+
catch (errorSpeech){
8717
+
console.log('Exception in D-ID Text-to-video API: ' + errorSpeech);
8718
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8719
+
aiomaticRmLoading(chatbut, instance);
8720
+
aiomatic_generator_working = false;
8721
+
}
8722
+
}
8723
+
speechRequest.send(speechData);
8724
+
}
8725
+
}
8726
+
else
8727
+
{
8728
+
if(aiomatic_chat_ajax_object.text_speech == 'didstream')
8729
+
{
8730
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
8731
+
response_data = aiomatic_stripHtmlTags(response_data);
8732
+
if(response_data != '')
8733
+
{
8734
+
if(avatarImageUrl != '' && did_app_id != '')
8735
+
{
8736
+
if(streamingEpicFail === false)
8737
+
{
8738
+
has_speech = true;
8739
+
myStreamObject.talkToDidStream(response_data);
8740
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8741
+
aiomatic_generator_working = false;
8742
+
}
8743
+
}
8744
+
}
8745
+
}
8746
+
else
8747
+
{
8748
+
if(aiomatic_chat_ajax_object.text_speech == 'azure')
8749
+
{
8750
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
8751
+
response_data = aiomatic_stripHtmlTags(response_data);
8752
+
if(response_data != '')
8753
+
{
8754
+
if(azure_speech_id != '')
8755
+
{
8756
+
if(streamingEpicFail === false)
8757
+
{
8758
+
has_speech = true;
8759
+
var ttsvoice = aiomatic_chat_ajax_object.azure_voice;
8760
+
var personalVoiceSpeakerProfileID = aiomatic_chat_ajax_object.azure_voice_profile;
8761
+
aiomaticRmLoading(chatbut, instance);
8762
+
azureSpeakText(response_data, ttsvoice, personalVoiceSpeakerProfileID);
8763
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8764
+
aiomatic_generator_working = false;
8765
+
}
8766
+
}
8767
+
}
8768
+
}
8769
+
else
8770
+
{
8771
+
if(aiomatic_chat_ajax_object.text_speech == 'free')
8772
+
{
8773
+
var T2S;
8774
+
if("speechSynthesis" in window || speechSynthesis)
8775
+
{
8776
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
8777
+
response_data = aiomatic_stripHtmlTags(response_data);
8778
+
if(response_data != '')
8779
+
{
8780
+
T2S = window.speechSynthesis || speechSynthesis;
8781
+
var utter = new SpeechSynthesisUtterance(response_data);
8782
+
var voiceSetting = aiomatic_chat_ajax_object.free_voice.split(";");
8783
+
var desiredVoiceName = voiceSetting[0].trim();
8784
+
var desiredLang = voiceSetting[1].trim();
8785
+
var voices = T2S.getVoices();
8786
+
var selectedVoice = voices.find(function(voice) {
8787
+
return voice.name === desiredVoiceName && voice.lang === desiredLang;
8788
+
});
8789
+
if (selectedVoice) {
8790
+
utter.voice = selectedVoice;
8791
+
utter.lang = selectedVoice.lang;
8792
+
}
8793
+
else
8794
+
{
8795
+
utter.lang = desiredLang;
8796
+
}
8797
+
T2S.speak(utter);
8798
+
}
8799
+
}
8800
+
}
8801
+
}
8802
+
}
8803
+
}
8804
+
}
8805
+
}
8806
+
}
8807
+
}
8808
+
if(has_speech === false)
8809
+
{
8810
+
if(error_generated == '')
8811
+
{
8812
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
8813
+
}
8814
+
aiomaticRmLoading(chatbut, instance);
8815
+
aiomatic_generator_working = false;
8816
+
}
8817
+
}
8818
+
}
8819
+
}
8820
+
function handleMessageEvent(e)
8821
+
{
8822
+
if(aiomatic_chat_ajax_object.model_type != 'claude')
8823
+
{
8824
+
var aiomatic_newline_before = false;
8825
+
var aiomatic_response_events = 0;
8826
+
var aiomatic_limitLines = 1;
8827
+
var currentContent = jQuery('#aiomatic_chat_history' + instance).html();
8828
+
var resultData = null;
8829
+
if(e.data == '[DONE]')
8830
+
{
8831
+
var hasFinishReason = true;
8832
+
}
8833
+
else
8834
+
{
8835
+
if(aiomatic_chat_ajax_object.model_type != 'google')
8836
+
{
8837
+
try
8838
+
{
8839
+
resultData = JSON.parse(e.data);
8840
+
}
8841
+
catch (e)
8842
+
{
8843
+
console.warn(e);
8844
+
aiomaticRmLoading(chatbut, instance);
8845
+
aiomatic_generator_working = false;
8846
+
eventGenerator.close();
8847
+
jQuery('#aistopbut' + instance).hide();
8848
+
return;
8849
+
}
8850
+
var hasFinishReason = resultData.choices &&
8851
+
resultData.choices[0] &&
8852
+
(resultData.choices[0].finish_reason === "stop" ||
8853
+
resultData.choices[0].finish_reason === "length");
8854
+
}
8855
+
}
8856
+
if(aiomatic_chat_ajax_object.model_type != 'google')
8857
+
{
8858
+
if(aiomatic_chat_ajax_object.model_type != 'ollama')
8859
+
{
8860
+
var content_generated = '';
8861
+
if(hasFinishReason){
8862
+
count_line += 1;
8863
+
aiomatic_response_events = 0;
8864
+
}
8865
+
else
8866
+
{
8867
+
var result = null;
8868
+
try
8869
+
{
8870
+
result = JSON.parse(e.data);
8871
+
}
8872
+
catch (e)
8873
+
{
8874
+
console.warn(e);
8875
+
aiomaticRmLoading(chatbut, instance);
8876
+
aiomatic_generator_working = false;
8877
+
eventGenerator.close();
8878
+
jQuery('#aistopbut' + instance).hide();
8879
+
return;
8880
+
};
8881
+
if(result.error !== undefined){
8882
+
if(result.error !== undefined){
8883
+
error_generated = result.error[0].message;
8884
+
}
8885
+
else
8886
+
{
8887
+
error_generated = JSON.stringify(result.error);
8888
+
}
8889
+
if(error_generated === undefined)
8890
+
{
8891
+
error_generated = result.error.message;
8892
+
}
8893
+
if(error_generated === undefined)
8894
+
{
8895
+
error_generated = result.error;
8896
+
}
8897
+
8898
+
console.log('Error while processing request(2): ' + error_generated);
8899
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + error_generated + '</div>');
8900
+
aiomaticRmLoading(chatbut, instance);
8901
+
aiomatic_generator_working = false;
8902
+
eventGenerator.close();
8903
+
jQuery('#aistopbut' + instance).hide();
8904
+
return;
8905
+
}
8906
+
else
8907
+
{
8908
+
if(aiomatic_chat_ajax_object.model_type == 'huggingface')
8909
+
{
8910
+
if (result.generated_text)
8911
+
{
8912
+
var hasFinishReason = true;
8913
+
count_line += 1;
8914
+
aiomatic_response_events = 0;
8915
+
}
8916
+
else
8917
+
{
8918
+
content_generated = result.token.text;
8919
+
}
8920
+
}
8921
+
else
8922
+
{
8923
+
if(result.choices && result.choices[0] && result.choices[0])
8924
+
{
8925
+
content_generated = result.choices[0].delta !== undefined ? (result.choices[0].delta.content !== undefined ? result.choices[0].delta.content : '') : result.choices[0].text;
8926
+
}
8927
+
else
8928
+
{
8929
+
content_generated = '';
8930
+
}
8931
+
}
8932
+
}
8933
+
if(aiomatic_chat_ajax_object.enable_html != true)
8934
+
{
8935
+
content_generated = aiomatic_esc_html(content_generated);
8936
+
}
8937
+
response_data += aiomatic_nl2br(content_generated);
8938
+
if(aiomatic_chat_ajax_object.strip_js == true)
8939
+
{
8940
+
response_data = response_data.replace(/<script[\s\S]*?<\/script>/gi, '');
8941
+
response_data = response_data.replace(/on\w+="[^"]*"/gi, '');
8942
+
}
8943
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
8944
+
response_data = processKatexMarkdown(response_data);
8945
+
}
8946
+
if(aiomatic_chat_ajax_object.markdown_parse == 'on')
8947
+
{
8948
+
response_data = aiomatic_parseMarkdown(response_data);
8949
+
}
8950
+
var appendx = '<div class="ai-wrapper">';
8951
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
8952
+
{
8953
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
8954
+
}
8955
+
appendx += '<div class="ai-bubble ai-other">' + response_data + '</div>';
8956
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
8957
+
{
8958
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
8959
+
}
8960
+
appendx += '</div>';
8961
+
if((content_generated === '\n' || content_generated === ' \n' || content_generated === '.\n' || content_generated === '\n\n' || content_generated === '.\n\n' || content_generated === '"\n') && aiomatic_response_events > 0 && currentContent !== ''){
8962
+
if(!aiomatic_newline_before) {
8963
+
aiomatic_newline_before = true;
8964
+
jQuery('#aiomatic_chat_history' + instance).html(currentContent + '<br /><br />');
8965
+
}
8966
+
}
8967
+
else if(content_generated === '\n' && aiomatic_response_events === 0 && currentContent === ''){
8968
+
8969
+
}
8970
+
else if(response_data == '')
8971
+
{
8972
+
aiomatic_newline_before = false;
8973
+
aiomatic_response_events += 1;
8974
+
}
8975
+
else{
8976
+
aiomatic_newline_before = false;
8977
+
aiomatic_response_events += 1;
8978
+
jQuery('#aiomatic_chat_history' + instance).html(initialContent + appendx);
8979
+
}
8980
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
8981
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
8982
+
renderMathInElement(katexContainer, {
8983
+
delimiters: [
8984
+
8985
+
{ left: '\\(', right: '\\)', display: false },
8986
+
{ left: '\\[', right: '\\]', display: true }
8987
+
],
8988
+
throwOnError: false
8989
+
});
8990
+
}
8991
+
if(result.choices !== undefined && result.choices[0] !== undefined && result.choices[0].delta !== undefined)
8992
+
{
8993
+
aiomatic_mergeDeep(func_call, result.choices[0].delta);
8994
+
if (result.choices[0].finish_reason === "tool_calls" || result.choices[0].finish_reason === "tool_call")
8995
+
{
8996
+
jQuery.ajax({
8997
+
type: 'POST',
8998
+
async: false,
8999
+
url: aiomatic_chat_ajax_object.ajax_url,
9000
+
data: {
9001
+
action: 'aiomatic_call_ai_function',
9002
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
9003
+
func_call: func_call
9004
+
},
9005
+
success: function(result)
9006
+
{
9007
+
if (typeof result !== "object" || result === null) {
9008
+
try {
9009
+
result = JSON.parse(result);
9010
+
} catch (error) {
9011
+
console.error("Failed to parse function JSON:", error);
9012
+
}
9013
+
}
9014
+
if(result.scope == 'fail')
9015
+
{
9016
+
console.log('Error while calling parsing functions: ' + result);
9017
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
9018
+
aiomaticRmLoading(chatbut, instance);
9019
+
aiomatic_generator_working = false;
9020
+
if (typeof eventGenerator !== 'undefined')
9021
+
{
9022
+
eventGenerator.close();
9023
+
jQuery('#aistopbut' + instance).hide();
9024
+
}
9025
+
return;
9026
+
}
9027
+
else
9028
+
{
9029
+
if(result.scope == 'response')
9030
+
{
9031
+
console.log('Recalling AI chat');
9032
+
if (typeof eventGenerator !== 'undefined')
9033
+
{
9034
+
eventGenerator.close();
9035
+
jQuery('#aistopbut' + instance).hide();
9036
+
}
9037
+
if(aiomatic_chat_ajax_object.enable_god_mode == '')
9038
+
{
9039
+
aiomatic_chat_ajax_object.enable_god_mode = 'off';
9040
+
}
9041
+
var internet_permission = aiomatic_chat_ajax_object.internet_access;
9042
+
if(jQuery('#aiomatic-globe-overlay' + instance).hasClass('aiomatic-globe-bar') && jQuery('#aiomatic-globe-overlay' + instance).is(':visible'))
9043
+
{
9044
+
internet_permission = 'disabled';
9045
+
}
9046
+
var eventURL = aiomatic_chat_ajax_object.stream_url;
9047
+
if(aiomatic_chat_ajax_object.bots_data && aiomatic_chat_ajax_object.strip_botname == '1')
9048
+
{
9049
+
aiomatic_chat_ajax_object.bots_data.forEach((relement) => input_text = input_text.replace('@' + relement.name, ''));
9050
+
}
9051
+
eventURL += '&input_text=' + encodeURIComponent(input_text);
9052
+
if(pdf_data != '')
9053
+
{
9054
+
eventURL += '&pdf_data=' + encodeURIComponent(pdf_data);
9055
+
}
9056
+
if(file_data != '')
9057
+
{
9058
+
eventURL += '&file_data=' + encodeURIComponent(file_data);
9059
+
}
9060
+
if(aiomatic_chat_ajax_object.user_token_cap_per_day != '')
9061
+
{
9062
+
eventURL += '&user_token_cap_per_day=' + encodeURIComponent(aiomatic_chat_ajax_object.user_token_cap_per_day);
9063
+
}
9064
+
if(aiomatic_chat_ajax_object.user_id != '')
9065
+
{
9066
+
eventURL += '&user_id=' + encodeURIComponent(aiomatic_chat_ajax_object.user_id);
9067
+
}
9068
+
if(aiomatic_chat_ajax_object.frequency != '')
9069
+
{
9070
+
eventURL += '&frequency=' + encodeURIComponent(aiomatic_chat_ajax_object.frequency);
9071
+
}
9072
+
if(aiomatic_chat_ajax_object.store_data != '')
9073
+
{
9074
+
eventURL += '&store_data=' + encodeURIComponent(aiomatic_chat_ajax_object.store_data);
9075
+
}
9076
+
if(aiomatic_chat_ajax_object.presence != '')
9077
+
{
9078
+
eventURL += '&presence=' + encodeURIComponent(aiomatic_chat_ajax_object.presence);
9079
+
}
9080
+
if(aiomatic_chat_ajax_object.top_p != '')
9081
+
{
9082
+
eventURL += '&top_p=' + encodeURIComponent(aiomatic_chat_ajax_object.top_p);
9083
+
}
9084
+
if(aiomatic_chat_ajax_object.temp != '')
9085
+
{
9086
+
eventURL += '&temp=' + encodeURIComponent(aiomatic_chat_ajax_object.temp);
9087
+
}
9088
+
if(aiomatic_chat_ajax_object.model != '')
9089
+
{
9090
+
eventURL += '&model=' + encodeURIComponent(aiomatic_chat_ajax_object.model);
9091
+
}
9092
+
if(ai_assistant_id != '')
9093
+
{
9094
+
eventURL += '&assistant_id=' + encodeURIComponent(ai_assistant_id);
9095
+
}
9096
+
if(th_id != '')
9097
+
{
9098
+
eventURL += '&thread_id=' + encodeURIComponent(th_id);
9099
+
}
9100
+
if(remember_string != '')
9101
+
{
9102
+
eventURL += '&remember_string=' + encodeURIComponent(remember_string);
9103
+
}
9104
+
if(is_modern_gpt != '')
9105
+
{
9106
+
eventURL += '&is_modern_gpt=' + encodeURIComponent(is_modern_gpt);
9107
+
}
9108
+
if(internet_permission != '')
9109
+
{
9110
+
eventURL += '&internet_access=' + encodeURIComponent(internet_permission);
9111
+
}
9112
+
if(aiomatic_chat_ajax_object.embeddings != '')
9113
+
{
9114
+
eventURL += '&embeddings=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings);
9115
+
}
9116
+
if(aiomatic_chat_ajax_object.embeddings_namespace != '')
9117
+
{
9118
+
eventURL += '&embeddings_namespace=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings_namespace);
9119
+
}
9120
+
if(user_question != '')
9121
+
{
9122
+
eventURL += '&user_question=' + encodeURIComponent(user_question);
9123
+
}
9124
+
if(enable_god_mode != '')
9125
+
{
9126
+
eventURL += '&enable_god_mode=' + encodeURIComponent(enable_god_mode);
9127
+
}
9128
+
if(mcp_servers != '')
9129
+
{
9130
+
eventURL += '&mcp_servers=' + encodeURIComponent(mcp_servers);
9131
+
}
9132
+
if(vision_file != '')
9133
+
{
9134
+
eventURL += '&vision_file=' + encodeURIComponent(vision_file);
9135
+
}
9136
+
var fnrez = JSON.stringify(result.data);
9137
+
eventURL += '&functions_result=' + encodeURIComponent(fnrez);
9138
+
if(eventURL.length > 2080)
9139
+
{
9140
+
console.log('URL too long, using alternative method');
9141
+
var unid = "id" + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
9142
+
aiChatUploadDataomatic(aiomatic_chat_ajax_object, unid, input_text, remember_string, user_question, fnrez);
9143
+
var eventURL = aiomatic_chat_ajax_object.stream_url;
9144
+
eventURL += '&input_text=0&remember_string=0&user_question=0&functions_result=0';
9145
+
if(pdf_data != '')
9146
+
{
9147
+
eventURL += '&pdf_data=' + encodeURIComponent(pdf_data);
9148
+
}
9149
+
if(file_data != '')
9150
+
{
9151
+
eventURL += '&file_data=' + encodeURIComponent(file_data);
9152
+
}
9153
+
if(aiomatic_chat_ajax_object.user_token_cap_per_day != '')
9154
+
{
9155
+
eventURL += '&user_token_cap_per_day=' + encodeURIComponent(aiomatic_chat_ajax_object.user_token_cap_per_day);
9156
+
}
9157
+
if(aiomatic_chat_ajax_object.user_id != '')
9158
+
{
9159
+
eventURL += '&user_id=' + encodeURIComponent(aiomatic_chat_ajax_object.user_id);
9160
+
}
9161
+
if(aiomatic_chat_ajax_object.frequency != '')
9162
+
{
9163
+
eventURL += '&frequency=' + encodeURIComponent(aiomatic_chat_ajax_object.frequency);
9164
+
}
9165
+
if(aiomatic_chat_ajax_object.store_data != '')
9166
+
{
9167
+
eventURL += '&store_data=' + encodeURIComponent(aiomatic_chat_ajax_object.store_data);
9168
+
}
9169
+
if(aiomatic_chat_ajax_object.presence != '')
9170
+
{
9171
+
eventURL += '&presence=' + encodeURIComponent(aiomatic_chat_ajax_object.presence);
9172
+
}
9173
+
if(aiomatic_chat_ajax_object.top_p != '')
9174
+
{
9175
+
eventURL += '&top_p=' + encodeURIComponent(aiomatic_chat_ajax_object.top_p);
9176
+
}
9177
+
if(aiomatic_chat_ajax_object.temp != '')
9178
+
{
9179
+
eventURL += '&temp=' + encodeURIComponent(aiomatic_chat_ajax_object.temp);
9180
+
}
9181
+
if(aiomatic_chat_ajax_object.model != '')
9182
+
{
9183
+
eventURL += '&model=' + encodeURIComponent(aiomatic_chat_ajax_object.model);
9184
+
}
9185
+
if(is_modern_gpt != '')
9186
+
{
9187
+
eventURL += '&is_modern_gpt=' + encodeURIComponent(is_modern_gpt);
9188
+
}
9189
+
if(internet_permission != '')
9190
+
{
9191
+
eventURL += '&internet_access=' + encodeURIComponent(internet_permission);
9192
+
}
9193
+
if(aiomatic_chat_ajax_object.embeddings != '')
9194
+
{
9195
+
eventURL += '&embeddings=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings);
9196
+
}
9197
+
if(aiomatic_chat_ajax_object.embeddings_namespace != '')
9198
+
{
9199
+
eventURL += '&embeddings_namespace=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings_namespace);
9200
+
}
9201
+
if(enable_god_mode != '')
9202
+
{
9203
+
eventURL += '&enable_god_mode=' + encodeURIComponent(enable_god_mode);
9204
+
}
9205
+
if(mcp_servers != '')
9206
+
{
9207
+
eventURL += '&mcp_servers=' + encodeURIComponent(mcp_servers);
9208
+
}
9209
+
if(vision_file != '')
9210
+
{
9211
+
eventURL += '&vision_file=' + encodeURIComponent(vision_file);
9212
+
}
9213
+
eventURL += '&bufferid=' + encodeURIComponent(unid);
9214
+
}
9215
+
func_call = {
9216
+
init_data: {
9217
+
pdf_data: pdf_data,
9218
+
file_data: file_data,
9219
+
user_token_cap_per_day: aiomatic_chat_ajax_object.user_token_cap_per_day,
9220
+
user_id: aiomatic_chat_ajax_object.user_id,
9221
+
store_data: aiomatic_chat_ajax_object.store_data,
9222
+
frequency: aiomatic_chat_ajax_object.frequency,
9223
+
presence: aiomatic_chat_ajax_object.presence,
9224
+
top_p: aiomatic_chat_ajax_object.top_p,
9225
+
temp: aiomatic_chat_ajax_object.temp,
9226
+
model: aiomatic_chat_ajax_object.model,
9227
+
input_text: input_text,
9228
+
remember_string: remember_string,
9229
+
is_modern_gpt: is_modern_gpt,
9230
+
user_question: user_question
9231
+
},
9232
+
};
9233
+
try
9234
+
{
9235
+
eventGenerator = new EventSource(eventURL);
9236
+
}
9237
+
catch(e)
9238
+
{
9239
+
console.log('Error in Event: ' + e);
9240
+
}
9241
+
eventGenerator.onerror = handleErrorEvent3;
9242
+
eventGenerator.addEventListener('message_stop', handleMessageStopEvent);
9243
+
eventGenerator.addEventListener('completion', handleCompletionEvent);
9244
+
eventGenerator.onmessage = handleMessageEvent;
9245
+
eventGenerator.addEventListener('content_block_delta', handleContentBlockDelta);
9246
+
9247
+
eventGenerator.addEventListener('response.output_text.delta', handleContentBlockDeltaResponses);
9248
+
eventGenerator.addEventListener('response.completed', handleResponsesMessageStopEvent);
9249
+
eventGenerator.addEventListener('response.failed', handleResponsesMessageFailedEvent);
9250
+
eventGenerator.addEventListener('response.incomplete', function (event) {
9251
+
console.log('Incomplete message');
9252
+
});
9253
+
eventGenerator.addEventListener('error', handleMessageErrorEvent);
9254
+
//eventGenerator.addEventListener('response.created', e => console.log('Response created'));
9255
+
//eventGenerator.addEventListener('response.in_progress', e => console.log('Response in progress'));
9256
+
9257
+
eventGenerator.addEventListener('response.output_item.added', handleOutputItemAdded);
9258
+
//eventGenerator.addEventListener('response.output_item.done', e => console.log('Output item done'));
9259
+
9260
+
//eventGenerator.addEventListener('response.content_part.added', e => console.log('Content part added'));
9261
+
//eventGenerator.addEventListener('response.content_part.done', e => console.log('Content part done'));
9262
+
9263
+
//eventGenerator.addEventListener('response.output_text.done', e => console.log('Output text done'));
9264
+
9265
+
//eventGenerator.addEventListener('response.output_text.annotation.added', e => console.log('Annotation added'));
9266
+
9267
+
//eventGenerator.addEventListener('response.refusal.delta', e => console.log('Refusal delta'));
9268
+
9269
+
//eventGenerator.addEventListener('response.reasoning_summary_part.added', e => console.log('Reasoning summary part added'));
9270
+
//eventGenerator.addEventListener('response.reasoning_summary_part.done', e => console.log('Reasoning summary part done'));
9271
+
9272
+
//eventGenerator.addEventListener('response.reasoning_summary_text.delta', e => console.log('Reasoning summary delta'));
9273
+
//eventGenerator.addEventListener('response.reasoning_summary_text.done', e => console.log('Reasoning summary done'));
9274
+
eventGenerator.addEventListener('response.refusal.done', handleRefusalDone);
9275
+
9276
+
eventGenerator.addEventListener('response.function_call_arguments.delta', handleFunctionCallArgumentsDelta);
9277
+
eventGenerator.addEventListener('response.function_call_arguments.done', handleFunctionCallArgumentsDone);
9278
+
9279
+
eventGenerator.addEventListener('response.file_search_call.in_progress', e => console.log('File search in progress'));
9280
+
eventGenerator.addEventListener('response.file_search_call.searching', e => console.log('File search searching'));
9281
+
eventGenerator.addEventListener('response.file_search_call.completed', e => console.log('File search completed'));
9282
+
9283
+
eventGenerator.addEventListener('response.web_search_call.in_progress', e => console.log('Web search in progress'));
9284
+
eventGenerator.addEventListener('response.web_search_call.searching', e => console.log('Web search searching'));
9285
+
eventGenerator.addEventListener('response.web_search_call.completed', e => console.log('Web search completed'));
9286
+
9287
+
}
9288
+
else
9289
+
{
9290
+
if(result.scope == 'end_message')
9291
+
{
9292
+
const inputField = document.getElementById('aiomatic_chat_input' + instance);
9293
+
inputField.disabled = true;
9294
+
inputField.chatended = true;
9295
+
const speechButton = document.getElementById('openai-chat-speech-button' + instance);
9296
+
if (speechButton) {
9297
+
speechButton.disabled = true;
9298
+
}
9299
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.conversation_ended + '</div>');
9300
+
aiomaticRmLoading(chatbut, instance);
9301
+
return;
9302
+
}
9303
+
if(result.scope == 'user_message')
9304
+
{
9305
+
var appendx = '<div class="ai-wrapper">';
9306
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
9307
+
{
9308
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
9309
+
}
9310
+
appendx += '<div class="ai-bubble ai-other">' + result.data + '</div>';
9311
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
9312
+
{
9313
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
9314
+
}
9315
+
appendx += '</div>';
9316
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
9317
+
appendx = processKatexMarkdown(appendx);
9318
+
}
9319
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
9320
+
appendx = aiomatic_parseMarkdown(appendx);
9321
+
}
9322
+
jQuery('#aiomatic_chat_history' + instance).html(initialContent + appendx);
9323
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
9324
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
9325
+
renderMathInElement(katexContainer, {
9326
+
delimiters: [
9327
+
9328
+
{ left: '\\(', right: '\\)', display: false },
9329
+
{ left: '\\[', right: '\\]', display: true }
9330
+
],
9331
+
throwOnError: false
9332
+
});
9333
+
}
9334
+
if (typeof eventGenerator !== 'undefined')
9335
+
{
9336
+
eventGenerator.close();
9337
+
jQuery('#aistopbut' + instance).hide();
9338
+
}
9339
+
aiomaticRmLoading(chatbut, instance);
9340
+
aiomatic_generator_working = false;
9341
+
}
9342
+
else
9343
+
{
9344
+
console.log('Unknown scope returned: ' + result);
9345
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
9346
+
aiomaticRmLoading(chatbut, instance);
9347
+
aiomatic_generator_working = false;
9348
+
if (typeof eventGenerator !== 'undefined')
9349
+
{
9350
+
eventGenerator.close();
9351
+
jQuery('#aistopbut' + instance).hide();
9352
+
}
9353
+
return;
9354
+
}
9355
+
}
9356
+
}
9357
+
},
9358
+
error: function(error) {
9359
+
console.log('Error while calling AI functions: ' + error.responseText);
9360
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
9361
+
aiomaticRmLoading(chatbut, instance);
9362
+
aiomatic_generator_working = false;
9363
+
if (typeof eventGenerator !== 'undefined')
9364
+
{
9365
+
eventGenerator.close();
9366
+
jQuery('#aistopbut' + instance).hide();
9367
+
}
9368
+
return;
9369
+
},
9370
+
});
9371
+
}
9372
+
}
9373
+
}
9374
+
}
9375
+
else
9376
+
{
9377
+
if(Object.hasOwn(resultData, 'done_reason'))
9378
+
{
9379
+
hasFinishReason = true;
9380
+
}
9381
+
if(hasFinishReason){
9382
+
count_line += 1;
9383
+
aiomatic_response_events = 0;
9384
+
}
9385
+
if(e.data == '[ERROR]')
9386
+
{
9387
+
error_generated = 'Failed to get chat response (error)!';
9388
+
console.log('Error while processing request: ' + error_generated);
9389
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + error_generated + '</div>');
9390
+
count_line += 1;
9391
+
}
9392
+
else
9393
+
{
9394
+
if(e.data !== '[DONE]')
9395
+
{
9396
+
if (resultData && resultData.message && typeof resultData.message.content !== 'undefined')
9397
+
{
9398
+
if(aiomatic_chat_ajax_object.enable_html != true)
9399
+
{
9400
+
var sanitizedCont = aiomatic_esc_html(resultData.message.content);
9401
+
}
9402
+
else
9403
+
{
9404
+
var sanitizedCont = resultData.message.content;
9405
+
}
9406
+
response_data += aiomatic_nl2br(sanitizedCont);
9407
+
if(aiomatic_chat_ajax_object.strip_js == true)
9408
+
{
9409
+
response_data = response_data.replace(/<script[\s\S]*?<\/script>/gi, '');
9410
+
response_data = response_data.replace(/on\w+="[^"]*"/gi, '');
9411
+
}
9412
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
9413
+
response_data = processKatexMarkdown(response_data);
9414
+
}
9415
+
if(aiomatic_chat_ajax_object.markdown_parse == 'on')
9416
+
{
9417
+
response_data = aiomatic_parseMarkdown(response_data);
9418
+
}
9419
+
var appendx = '<div class="ai-wrapper">';
9420
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
9421
+
{
9422
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
9423
+
}
9424
+
appendx += '<div class="ai-bubble ai-other">' + response_data + '</div>';
9425
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
9426
+
{
9427
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
9428
+
}
9429
+
appendx += '</div>';
9430
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
9431
+
appendx = processKatexMarkdown(appendx);
9432
+
}
9433
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
9434
+
appendx = aiomatic_parseMarkdown(appendx);
9435
+
}
9436
+
aiomatic_response_events += 1;
9437
+
jQuery('#aiomatic_chat_history' + instance).html(initialContent + appendx);
9438
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
9439
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
9440
+
renderMathInElement(katexContainer, {
9441
+
delimiters: [
9442
+
9443
+
{ left: '\\(', right: '\\)', display: false },
9444
+
{ left: '\\[', right: '\\]', display: true }
9445
+
],
9446
+
throwOnError: false
9447
+
});
9448
+
}
9449
+
}
9450
+
else
9451
+
{
9452
+
error_generated = 'Failed to get chat response (invalida data)!';
9453
+
console.log('Streaming error: ' + JSON.stringify(resultData));
9454
+
if(resultData && resultData.error && resultData.error[0] && typeof resultData.error[0].message !== 'undefined')
9455
+
{
9456
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + resultData.error[0].message + '</div>');
9457
+
}
9458
+
else
9459
+
{
9460
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + JSON.stringify(resultData) + '</div>');
9461
+
}
9462
+
count_line += 1;
9463
+
}
9464
+
}
9465
+
}
9466
+
}
9467
+
}
9468
+
else
9469
+
{
9470
+
if(hasFinishReason){
9471
+
count_line += 1;
9472
+
aiomatic_response_events = 0;
9473
+
}
9474
+
if(e.data == '[ERROR]')
9475
+
{
9476
+
error_generated = 'Failed to get chat response!';
9477
+
console.log('Error while processing request: ' + error_generated);
9478
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + error_generated + '</div>');
9479
+
count_line += 1;
9480
+
}
9481
+
else
9482
+
{
9483
+
if(e.data.startsWith('[AIMOGENTOOLCALLGOOGLE]'))
9484
+
{
9485
+
var tooldata = e.data.substring('[AIMOGENTOOLCALLGOOGLE]'.length).trim();
9486
+
try
9487
+
{
9488
+
var jsontool = JSON.parse(tooldata);
9489
+
jQuery.ajax({
9490
+
type: 'POST',
9491
+
async: false,
9492
+
url: aiomatic_chat_ajax_object.ajax_url,
9493
+
data: {
9494
+
action: 'aiomatic_call_google_ai_function',
9495
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
9496
+
func_call: jsontool
9497
+
},
9498
+
success: function(result)
9499
+
{
9500
+
if (typeof result !== "object" || result === null) {
9501
+
try {
9502
+
result = JSON.parse(result);
9503
+
} catch (error) {
9504
+
console.error("Failed to parse function JSON:", error);
9505
+
}
9506
+
}
9507
+
if(result.scope == 'fail')
9508
+
{
9509
+
console.log('Error while calling parsing functions: ' + result);
9510
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
9511
+
aiomaticRmLoading(chatbut, instance);
9512
+
aiomatic_generator_working = false;
9513
+
if (typeof eventGenerator !== 'undefined')
9514
+
{
9515
+
eventGenerator.close();
9516
+
jQuery('#aistopbut' + instance).hide();
9517
+
}
9518
+
return;
9519
+
}
9520
+
else
9521
+
{
9522
+
if(result.scope == 'response')
9523
+
{
9524
+
console.log('Recalling Google AI chat');
9525
+
if (typeof eventGenerator !== 'undefined')
9526
+
{
9527
+
eventGenerator.close();
9528
+
jQuery('#aistopbut' + instance).hide();
9529
+
}
9530
+
if(aiomatic_chat_ajax_object.enable_god_mode == '')
9531
+
{
9532
+
aiomatic_chat_ajax_object.enable_god_mode = 'off';
9533
+
}
9534
+
var internet_permission = aiomatic_chat_ajax_object.internet_access;
9535
+
if(jQuery('#aiomatic-globe-overlay' + instance).hasClass('aiomatic-globe-bar') && jQuery('#aiomatic-globe-overlay' + instance).is(':visible'))
9536
+
{
9537
+
internet_permission = 'disabled';
9538
+
}
9539
+
var eventURL = aiomatic_chat_ajax_object.stream_url;
9540
+
if(aiomatic_chat_ajax_object.bots_data && aiomatic_chat_ajax_object.strip_botname == '1')
9541
+
{
9542
+
aiomatic_chat_ajax_object.bots_data.forEach((relement) => input_text = input_text.replace('@' + relement.name, ''));
9543
+
}
9544
+
eventURL += '&input_text=' + encodeURIComponent(input_text);
9545
+
if(pdf_data != '')
9546
+
{
9547
+
eventURL += '&pdf_data=' + encodeURIComponent(pdf_data);
9548
+
}
9549
+
if(file_data != '')
9550
+
{
9551
+
eventURL += '&file_data=' + encodeURIComponent(file_data);
9552
+
}
9553
+
if(aiomatic_chat_ajax_object.user_token_cap_per_day != '')
9554
+
{
9555
+
eventURL += '&user_token_cap_per_day=' + encodeURIComponent(aiomatic_chat_ajax_object.user_token_cap_per_day);
9556
+
}
9557
+
if(aiomatic_chat_ajax_object.user_id != '')
9558
+
{
9559
+
eventURL += '&user_id=' + encodeURIComponent(aiomatic_chat_ajax_object.user_id);
9560
+
}
9561
+
if(aiomatic_chat_ajax_object.frequency != '')
9562
+
{
9563
+
eventURL += '&frequency=' + encodeURIComponent(aiomatic_chat_ajax_object.frequency);
9564
+
}
9565
+
if(aiomatic_chat_ajax_object.store_data != '')
9566
+
{
9567
+
eventURL += '&store_data=' + encodeURIComponent(aiomatic_chat_ajax_object.store_data);
9568
+
}
9569
+
if(aiomatic_chat_ajax_object.presence != '')
9570
+
{
9571
+
eventURL += '&presence=' + encodeURIComponent(aiomatic_chat_ajax_object.presence);
9572
+
}
9573
+
if(aiomatic_chat_ajax_object.top_p != '')
9574
+
{
9575
+
eventURL += '&top_p=' + encodeURIComponent(aiomatic_chat_ajax_object.top_p);
9576
+
}
9577
+
if(aiomatic_chat_ajax_object.temp != '')
9578
+
{
9579
+
eventURL += '&temp=' + encodeURIComponent(aiomatic_chat_ajax_object.temp);
9580
+
}
9581
+
if(aiomatic_chat_ajax_object.model != '')
9582
+
{
9583
+
eventURL += '&model=' + encodeURIComponent(aiomatic_chat_ajax_object.model);
9584
+
}
9585
+
if(ai_assistant_id != '')
9586
+
{
9587
+
eventURL += '&assistant_id=' + encodeURIComponent(ai_assistant_id);
9588
+
}
9589
+
if(th_id != '')
9590
+
{
9591
+
eventURL += '&thread_id=' + encodeURIComponent(th_id);
9592
+
}
9593
+
if(remember_string != '')
9594
+
{
9595
+
eventURL += '&remember_string=' + encodeURIComponent(remember_string);
9596
+
}
9597
+
if(is_modern_gpt != '')
9598
+
{
9599
+
eventURL += '&is_modern_gpt=' + encodeURIComponent(is_modern_gpt);
9600
+
}
9601
+
if(internet_permission != '')
9602
+
{
9603
+
eventURL += '&internet_access=' + encodeURIComponent(internet_permission);
9604
+
}
9605
+
if(aiomatic_chat_ajax_object.embeddings != '')
9606
+
{
9607
+
eventURL += '&embeddings=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings);
9608
+
}
9609
+
if(aiomatic_chat_ajax_object.embeddings_namespace != '')
9610
+
{
9611
+
eventURL += '&embeddings_namespace=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings_namespace);
9612
+
}
9613
+
if(user_question != '')
9614
+
{
9615
+
eventURL += '&user_question=' + encodeURIComponent(user_question);
9616
+
}
9617
+
if(enable_god_mode != '')
9618
+
{
9619
+
eventURL += '&enable_god_mode=' + encodeURIComponent(enable_god_mode);
9620
+
}
9621
+
if(mcp_servers != '')
9622
+
{
9623
+
eventURL += '&mcp_servers=' + encodeURIComponent(mcp_servers);
9624
+
}
9625
+
if(vision_file != '')
9626
+
{
9627
+
eventURL += '&vision_file=' + encodeURIComponent(vision_file);
9628
+
}
9629
+
var fnrez = JSON.stringify(result.data);
9630
+
eventURL += '&functions_result=' + encodeURIComponent(fnrez);
9631
+
if(eventURL.length > 2080)
9632
+
{
9633
+
console.log('URL too long, using alternative method');
9634
+
var unid = "id" + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
9635
+
aiChatUploadDataomatic(aiomatic_chat_ajax_object, unid, input_text, remember_string, user_question, fnrez);
9636
+
var eventURL = aiomatic_chat_ajax_object.stream_url;
9637
+
eventURL += '&input_text=0&remember_string=0&user_question=0&functions_result=0';
9638
+
if(pdf_data != '')
9639
+
{
9640
+
eventURL += '&pdf_data=' + encodeURIComponent(pdf_data);
9641
+
}
9642
+
if(file_data != '')
9643
+
{
9644
+
eventURL += '&file_data=' + encodeURIComponent(file_data);
9645
+
}
9646
+
if(aiomatic_chat_ajax_object.user_token_cap_per_day != '')
9647
+
{
9648
+
eventURL += '&user_token_cap_per_day=' + encodeURIComponent(aiomatic_chat_ajax_object.user_token_cap_per_day);
9649
+
}
9650
+
if(aiomatic_chat_ajax_object.user_id != '')
9651
+
{
9652
+
eventURL += '&user_id=' + encodeURIComponent(aiomatic_chat_ajax_object.user_id);
9653
+
}
9654
+
if(aiomatic_chat_ajax_object.frequency != '')
9655
+
{
9656
+
eventURL += '&frequency=' + encodeURIComponent(aiomatic_chat_ajax_object.frequency);
9657
+
}
9658
+
if(aiomatic_chat_ajax_object.store_data != '')
9659
+
{
9660
+
eventURL += '&store_data=' + encodeURIComponent(aiomatic_chat_ajax_object.store_data);
9661
+
}
9662
+
if(aiomatic_chat_ajax_object.presence != '')
9663
+
{
9664
+
eventURL += '&presence=' + encodeURIComponent(aiomatic_chat_ajax_object.presence);
9665
+
}
9666
+
if(aiomatic_chat_ajax_object.top_p != '')
9667
+
{
9668
+
eventURL += '&top_p=' + encodeURIComponent(aiomatic_chat_ajax_object.top_p);
9669
+
}
9670
+
if(aiomatic_chat_ajax_object.temp != '')
9671
+
{
9672
+
eventURL += '&temp=' + encodeURIComponent(aiomatic_chat_ajax_object.temp);
9673
+
}
9674
+
if(aiomatic_chat_ajax_object.model != '')
9675
+
{
9676
+
eventURL += '&model=' + encodeURIComponent(aiomatic_chat_ajax_object.model);
9677
+
}
9678
+
if(is_modern_gpt != '')
9679
+
{
9680
+
eventURL += '&is_modern_gpt=' + encodeURIComponent(is_modern_gpt);
9681
+
}
9682
+
if(internet_permission != '')
9683
+
{
9684
+
eventURL += '&internet_access=' + encodeURIComponent(internet_permission);
9685
+
}
9686
+
if(aiomatic_chat_ajax_object.embeddings != '')
9687
+
{
9688
+
eventURL += '&embeddings=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings);
9689
+
}
9690
+
if(aiomatic_chat_ajax_object.embeddings_namespace != '')
9691
+
{
9692
+
eventURL += '&embeddings_namespace=' + encodeURIComponent(aiomatic_chat_ajax_object.embeddings_namespace);
9693
+
}
9694
+
if(enable_god_mode != '')
9695
+
{
9696
+
eventURL += '&enable_god_mode=' + encodeURIComponent(enable_god_mode);
9697
+
}
9698
+
if(mcp_servers != '')
9699
+
{
9700
+
eventURL += '&mcp_servers=' + encodeURIComponent(mcp_servers);
9701
+
}
9702
+
if(vision_file != '')
9703
+
{
9704
+
eventURL += '&vision_file=' + encodeURIComponent(vision_file);
9705
+
}
9706
+
eventURL += '&bufferid=' + encodeURIComponent(unid);
9707
+
}
9708
+
func_call = {
9709
+
init_data: {
9710
+
pdf_data: pdf_data,
9711
+
file_data: file_data,
9712
+
user_token_cap_per_day: aiomatic_chat_ajax_object.user_token_cap_per_day,
9713
+
user_id: aiomatic_chat_ajax_object.user_id,
9714
+
store_data: aiomatic_chat_ajax_object.store_data,
9715
+
frequency: aiomatic_chat_ajax_object.frequency,
9716
+
presence: aiomatic_chat_ajax_object.presence,
9717
+
top_p: aiomatic_chat_ajax_object.top_p,
9718
+
temp: aiomatic_chat_ajax_object.temp,
9719
+
model: aiomatic_chat_ajax_object.model,
9720
+
input_text: input_text,
9721
+
remember_string: remember_string,
9722
+
is_modern_gpt: is_modern_gpt,
9723
+
user_question: user_question
9724
+
},
9725
+
};
9726
+
try
9727
+
{
9728
+
eventGenerator.close();
9729
+
eventGenerator = new EventSource(eventURL);
9730
+
}
9731
+
catch(e)
9732
+
{
9733
+
console.log('Error in Event: ' + e);
9734
+
}
9735
+
eventGenerator.onerror = handleErrorEvent4;
9736
+
eventGenerator.addEventListener('message_stop', handleMessageStopEvent);
9737
+
eventGenerator.addEventListener('completion', handleCompletionEvent);
9738
+
eventGenerator.onmessage = handleMessageEvent;
9739
+
eventGenerator.addEventListener('content_block_delta', handleContentBlockDelta);
9740
+
9741
+
eventGenerator.addEventListener('response.output_text.delta', handleContentBlockDeltaResponses);
9742
+
eventGenerator.addEventListener('response.completed', handleResponsesMessageStopEvent);
9743
+
eventGenerator.addEventListener('response.failed', handleResponsesMessageFailedEvent);
9744
+
eventGenerator.addEventListener('response.incomplete', function (event) {
9745
+
console.log('Incomplete message');
9746
+
});
9747
+
eventGenerator.addEventListener('error', handleMessageErrorEvent);
9748
+
//eventGenerator.addEventListener('response.created', e => console.log('Response created'));
9749
+
//eventGenerator.addEventListener('response.in_progress', e => console.log('Response in progress'));
9750
+
9751
+
eventGenerator.addEventListener('response.output_item.added', handleOutputItemAdded);
9752
+
//eventGenerator.addEventListener('response.output_item.done', e => console.log('Output item done'));
9753
+
9754
+
//eventGenerator.addEventListener('response.content_part.added', e => console.log('Content part added'));
9755
+
//eventGenerator.addEventListener('response.content_part.done', e => console.log('Content part done'));
9756
+
9757
+
//eventGenerator.addEventListener('response.output_text.done', e => console.log('Output text done'));
9758
+
9759
+
//eventGenerator.addEventListener('response.output_text.annotation.added', e => console.log('Annotation added'));
9760
+
9761
+
//eventGenerator.addEventListener('response.refusal.delta', e => console.log('Refusal delta'));
9762
+
9763
+
//eventGenerator.addEventListener('response.reasoning_summary_part.added', e => console.log('Reasoning summary part added'));
9764
+
//eventGenerator.addEventListener('response.reasoning_summary_part.done', e => console.log('Reasoning summary part done'));
9765
+
9766
+
//eventGenerator.addEventListener('response.reasoning_summary_text.delta', e => console.log('Reasoning summary delta'));
9767
+
//eventGenerator.addEventListener('response.reasoning_summary_text.done', e => console.log('Reasoning summary done'));
9768
+
eventGenerator.addEventListener('response.refusal.done', handleRefusalDone);
9769
+
9770
+
eventGenerator.addEventListener('response.function_call_arguments.delta', handleFunctionCallArgumentsDelta);
9771
+
eventGenerator.addEventListener('response.function_call_arguments.done', handleFunctionCallArgumentsDone);
9772
+
9773
+
eventGenerator.addEventListener('response.file_search_call.in_progress', e => console.log('File search in progress'));
9774
+
eventGenerator.addEventListener('response.file_search_call.searching', e => console.log('File search searching'));
9775
+
eventGenerator.addEventListener('response.file_search_call.completed', e => console.log('File search completed'));
9776
+
9777
+
eventGenerator.addEventListener('response.web_search_call.in_progress', e => console.log('Web search in progress'));
9778
+
eventGenerator.addEventListener('response.web_search_call.searching', e => console.log('Web search searching'));
9779
+
eventGenerator.addEventListener('response.web_search_call.completed', e => console.log('Web search completed'));
9780
+
9781
+
}
9782
+
else
9783
+
{
9784
+
if(result.scope == 'end_message')
9785
+
{
9786
+
const inputField = document.getElementById('aiomatic_chat_input' + instance);
9787
+
inputField.disabled = true;
9788
+
inputField.chatended = true;
9789
+
const speechButton = document.getElementById('openai-chat-speech-button' + instance);
9790
+
if (speechButton) {
9791
+
speechButton.disabled = true;
9792
+
}
9793
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.conversation_ended + '</div>');
9794
+
aiomaticRmLoading(chatbut, instance);
9795
+
return;
9796
+
}
9797
+
if(result.scope == 'user_message')
9798
+
{
9799
+
var appendx = '<div class="ai-wrapper">';
9800
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
9801
+
{
9802
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
9803
+
}
9804
+
appendx += '<div class="ai-bubble ai-other">' + result.data + '</div>';
9805
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
9806
+
{
9807
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
9808
+
}
9809
+
appendx += '</div>';
9810
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
9811
+
appendx = processKatexMarkdown(appendx);
9812
+
}
9813
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
9814
+
appendx = aiomatic_parseMarkdown(appendx);
9815
+
}
9816
+
jQuery('#aiomatic_chat_history' + instance).html(initialContent + appendx);
9817
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
9818
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
9819
+
renderMathInElement(katexContainer, {
9820
+
delimiters: [
9821
+
9822
+
{ left: '\\(', right: '\\)', display: false },
9823
+
{ left: '\\[', right: '\\]', display: true }
9824
+
],
9825
+
throwOnError: false
9826
+
});
9827
+
}
9828
+
if (typeof eventGenerator !== 'undefined')
9829
+
{
9830
+
eventGenerator.close();
9831
+
jQuery('#aistopbut' + instance).hide();
9832
+
}
9833
+
aiomaticRmLoading(chatbut, instance);
9834
+
aiomatic_generator_working = false;
9835
+
}
9836
+
else
9837
+
{
9838
+
console.log('Unknown scope returned: ' + result);
9839
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
9840
+
aiomaticRmLoading(chatbut, instance);
9841
+
aiomatic_generator_working = false;
9842
+
if (typeof eventGenerator !== 'undefined')
9843
+
{
9844
+
eventGenerator.close();
9845
+
jQuery('#aistopbut' + instance).hide();
9846
+
}
9847
+
return;
9848
+
}
9849
+
}
9850
+
}
9851
+
},
9852
+
error: function(error) {
9853
+
console.log('Error while calling AI functions: ' + error.responseText);
9854
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
9855
+
aiomaticRmLoading(chatbut, instance);
9856
+
aiomatic_generator_working = false;
9857
+
if (typeof eventGenerator !== 'undefined')
9858
+
{
9859
+
eventGenerator.close();
9860
+
jQuery('#aistopbut' + instance).hide();
9861
+
}
9862
+
return;
9863
+
},
9864
+
});
9865
+
}
9866
+
catch (e)
9867
+
{
9868
+
console.warn(e);
9869
+
error_generated = 'Failed to get streamed chat response!';
9870
+
console.log('Error while processing request: ' + error_generated);
9871
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + error_generated + '</div>');
9872
+
count_line += 1;
9873
+
}
9874
+
}
9875
+
else
9876
+
{
9877
+
if(e.data !== '[DONE]')
9878
+
{
9879
+
if(aiomatic_chat_ajax_object.enable_html != true)
9880
+
{
9881
+
var sanitizedData = aiomatic_esc_html(e.data);
9882
+
}
9883
+
else
9884
+
{
9885
+
var sanitizedData = e.data;
9886
+
}
9887
+
response_data += aiomatic_nl2br(sanitizedData);
9888
+
if(aiomatic_chat_ajax_object.strip_js == true)
9889
+
{
9890
+
response_data = response_data.replace(/<script[\s\S]*?<\/script>/gi, '');
9891
+
response_data = response_data.replace(/on\w+="[^"]*"/gi, '');
9892
+
}
9893
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
9894
+
response_data = processKatexMarkdown(response_data);
9895
+
}
9896
+
if(aiomatic_chat_ajax_object.markdown_parse == 'on')
9897
+
{
9898
+
response_data = aiomatic_parseMarkdown(response_data);
9899
+
}
9900
+
var appendx = '<div class="ai-wrapper">';
9901
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
9902
+
{
9903
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
9904
+
}
9905
+
appendx += '<div class="ai-bubble ai-other">' + response_data + '</div>';
9906
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
9907
+
{
9908
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
9909
+
}
9910
+
appendx += '</div>';
9911
+
aiomatic_response_events += 1;
9912
+
jQuery('#aiomatic_chat_history' + instance).html(initialContent + appendx);
9913
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
9914
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
9915
+
renderMathInElement(katexContainer, {
9916
+
delimiters: [
9917
+
9918
+
{ left: '\\(', right: '\\)', display: false },
9919
+
{ left: '\\[', right: '\\]', display: true }
9920
+
],
9921
+
throwOnError: false
9922
+
});
9923
+
}
9924
+
}
9925
+
}
9926
+
}
9927
+
}
9928
+
if(count_line >= aiomatic_limitLines)
9929
+
{
9930
+
eventGenerator.close();
9931
+
jQuery('#aistopbut' + instance).hide();
9932
+
var x_input_text = jQuery('#aiomatic_chat_history' + instance).html();
9933
+
if((persistent != 'off' && persistent != '0' && persistent != '') && user_id != '0' && error_generated == '')
9934
+
{
9935
+
var save_persistent = x_input_text;
9936
+
if(persistent == 'vector')
9937
+
{
9938
+
save_persistent = user_question;
9939
+
}
9940
+
var saving_index = '';
9941
+
var main_index = '';
9942
+
if(persistent == 'history')
9943
+
{
9944
+
saving_index = jQuery('#chat-log-identifier' + instance).val();
9945
+
main_index = jQuery('#chat-main-identifier' + instance).val();
9946
+
}
9947
+
jQuery.ajax({
9948
+
type: 'POST',
9949
+
url: aiomatic_chat_ajax_object.ajax_url,
9950
+
data: {
9951
+
action: 'aiomatic_user_meta_save',
9952
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
9953
+
persistent: persistent,
9954
+
thread_id: aiomatic_chat_ajax_object.thread_id,
9955
+
x_input_text: save_persistent,
9956
+
user_id: user_id,
9957
+
saving_index: saving_index,
9958
+
main_index: main_index
9959
+
},
9960
+
success: function(result) {
9961
+
if(result.name && result.msg)
9962
+
{
9963
+
var logsdrop = jQuery('#chat-logs-dropdown' + instance);
9964
+
if(logsdrop)
9965
+
{
9966
+
var newChatLogItem = jQuery('<div class="chat-log-item" id="chat-log-item' + saving_index + '" data-id="' + saving_index + '" onclick="aiomatic_trigger_chat_logs(\'' + saving_index + '\', \'' + instance + '\')">' + result.name + '<span onclick="aiomatic_remove_chat_logs(event, \'' + saving_index + '\', \'' + instance + '\');" class="aiomatic-remove-item">X</span></div>');
9967
+
var chatLogNew = logsdrop.find('.chat-log-new');
9968
+
if (chatLogNew.length)
9969
+
{
9970
+
var nextSibling = chatLogNew.next();
9971
+
if (nextSibling.length && nextSibling.hasClass('date-group-label'))
9972
+
{
9973
+
newChatLogItem.insertAfter(nextSibling);
9974
+
}
9975
+
else
9976
+
{
9977
+
newChatLogItem.insertAfter(chatLogNew);
9978
+
}
9979
+
}
9980
+
else
9981
+
{
9982
+
logsdrop.append(newChatLogItem);
9983
+
}
9984
+
}
9985
+
}
9986
+
},
9987
+
error: function(error) {
9988
+
console.log('Error while saving persistent user log: ' + error.responseText);
9989
+
},
9990
+
});
9991
+
}
9992
+
if(error_generated == '')
9993
+
{
9994
+
jQuery.ajax({
9995
+
type: 'POST',
9996
+
url: aiomatic_chat_ajax_object.ajax_url,
9997
+
data: {
9998
+
action: 'aiomatic_record_user_usage',
9999
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
10000
+
user_id: user_id,
10001
+
input_text: input_text,
10002
+
response_text: response_data,
10003
+
model: model,
10004
+
temp: temp,
10005
+
vision_file: vision_file,
10006
+
user_token_cap_per_day: aiomatic_chat_ajax_object.user_token_cap_per_day,
10007
+
source: 'chat'
10008
+
},
10009
+
success: function()
10010
+
{
10011
+
},
10012
+
error: function(error) {
10013
+
console.log('Error while saving user data: ' + error.responseText);
10014
+
},
10015
+
});
10016
+
}
10017
+
if(error_generated == '')
10018
+
{
10019
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10020
+
}
10021
+
var has_speech = false;
10022
+
if(aiomatic_chat_ajax_object.receive_message_sound != '')
10023
+
{
10024
+
var snd = new Audio(aiomatic_chat_ajax_object.receive_message_sound);
10025
+
snd.play();
10026
+
}
10027
+
if(error_generated == '' && !jQuery('.aiomatic-gg-unmute').length)
10028
+
{
10029
+
if(aiomatic_chat_ajax_object.text_speech == 'elevenlabs')
10030
+
{
10031
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
10032
+
response_data = aiomatic_stripHtmlTags(response_data);
10033
+
if(response_data != '')
10034
+
{
10035
+
has_speech = true;
10036
+
let speechData = new FormData();
10037
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
10038
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
10039
+
speechData.append('x_input_text', response_data);
10040
+
speechData.append('action', 'aiomatic_get_elevenlabs_voice_chat');
10041
+
var speechRequest = new XMLHttpRequest();
10042
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
10043
+
speechRequest.responseType = "arraybuffer";
10044
+
speechRequest.ontimeout = () => {
10045
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
10046
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10047
+
aiomaticRmLoading(chatbut, instance);
10048
+
aiomatic_generator_working = false;
10049
+
};
10050
+
speechRequest.onerror = function ()
10051
+
{
10052
+
console.error("Network Error");
10053
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10054
+
aiomaticRmLoading(chatbut, instance);
10055
+
aiomatic_generator_working = false;
10056
+
};
10057
+
speechRequest.onabort = function ()
10058
+
{
10059
+
console.error("The request was aborted.");
10060
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10061
+
aiomaticRmLoading(chatbut, instance);
10062
+
aiomatic_generator_working = false;
10063
+
};
10064
+
speechRequest.onload = function () {
10065
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
10066
+
var fr = new FileReader();
10067
+
fr.onload = function () {
10068
+
var fileText = this.result;
10069
+
try {
10070
+
var errorMessage = JSON.parse(fileText);
10071
+
console.log('ElevenLabs API failed: ' + errorMessage.msg);
10072
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10073
+
aiomaticRmLoading(chatbut, instance);
10074
+
aiomatic_generator_working = false;
10075
+
} catch (errorBlob) {
10076
+
var blobUrl = URL.createObjectURL(blob);
10077
+
var audioElement = document.createElement('audio');
10078
+
audioElement.src = blobUrl;
10079
+
audioElement.controls = true;
10080
+
audioElement.style.marginTop = "2px";
10081
+
audioElement.style.width = "100%";
10082
+
audioElement.id = 'audio-element-' + instance;
10083
+
audioElement.addEventListener("error", function(event) {
10084
+
console.error("Error loading or playing the audio: ", event);
10085
+
});
10086
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
10087
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
10088
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
10089
+
{
10090
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
10091
+
var waveform = WaveSurfer.create({
10092
+
container: '#waveform-container' + instance,
10093
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
10094
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
10095
+
backend: 'MediaElement',
10096
+
height: 60,
10097
+
barWidth: 2,
10098
+
responsive: true, mediaControls: false, interact: false
10099
+
});
10100
+
waveform.setMuted(true);
10101
+
waveform.load(blobUrl);
10102
+
waveform.on('ready', function () {
10103
+
waveform.play();
10104
+
});
10105
+
audioElement.addEventListener('play', function () {
10106
+
waveform.play();
10107
+
});
10108
+
audioElement.addEventListener('pause', function () {
10109
+
waveform.pause();
10110
+
});
10111
+
}
10112
+
else
10113
+
{
10114
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10115
+
}
10116
+
audioElement.play();
10117
+
aiomaticRmLoading(chatbut, instance);
10118
+
aiomatic_generator_working = false;
10119
+
}
10120
+
}
10121
+
fr.readAsText(blob);
10122
+
}
10123
+
speechRequest.send(speechData);
10124
+
}
10125
+
}
10126
+
else
10127
+
{
10128
+
if(aiomatic_chat_ajax_object.text_speech == 'openai')
10129
+
{
10130
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
10131
+
response_data = aiomatic_stripHtmlTags(response_data);
10132
+
if(response_data != '')
10133
+
{
10134
+
has_speech = true;
10135
+
let speechData = new FormData();
10136
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
10137
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
10138
+
speechData.append('x_input_text', response_data);
10139
+
speechData.append('action', 'aiomatic_get_openai_voice_chat');
10140
+
var speechRequest = new XMLHttpRequest();
10141
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
10142
+
speechRequest.responseType = "arraybuffer";
10143
+
speechRequest.ontimeout = () => {
10144
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
10145
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10146
+
aiomaticRmLoading(chatbut, instance);
10147
+
aiomatic_generator_working = false;
10148
+
};
10149
+
speechRequest.onerror = function ()
10150
+
{
10151
+
console.error("Network Error");
10152
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10153
+
aiomaticRmLoading(chatbut, instance);
10154
+
aiomatic_generator_working = false;
10155
+
};
10156
+
speechRequest.onabort = function ()
10157
+
{
10158
+
console.error("The request was aborted.");
10159
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10160
+
aiomaticRmLoading(chatbut, instance);
10161
+
aiomatic_generator_working = false;
10162
+
};
10163
+
speechRequest.onload = function () {
10164
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
10165
+
var fr = new FileReader();
10166
+
fr.onload = function () {
10167
+
var fileText = this.result;
10168
+
try {
10169
+
var errorMessage = JSON.parse(fileText);
10170
+
console.log('OpenAI TTS API failed: ' + errorMessage.msg);
10171
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10172
+
aiomaticRmLoading(chatbut, instance);
10173
+
aiomatic_generator_working = false;
10174
+
} catch (errorBlob) {
10175
+
var blobUrl = URL.createObjectURL(blob);
10176
+
var audioElement = document.createElement('audio');
10177
+
audioElement.src = blobUrl;
10178
+
audioElement.controls = true;
10179
+
audioElement.style.marginTop = "2px";
10180
+
audioElement.style.width = "100%";
10181
+
audioElement.id = 'audio-element-' + instance;
10182
+
audioElement.addEventListener("error", function(event) {
10183
+
console.error("Error loading or playing the audio: ", event);
10184
+
});
10185
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
10186
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
10187
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
10188
+
{
10189
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
10190
+
var waveform = WaveSurfer.create({
10191
+
container: '#waveform-container' + instance,
10192
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
10193
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
10194
+
backend: 'MediaElement',
10195
+
height: 60,
10196
+
barWidth: 2,
10197
+
responsive: true, mediaControls: false, interact: false
10198
+
});
10199
+
waveform.setMuted(true);
10200
+
waveform.load(blobUrl);
10201
+
waveform.on('ready', function () {
10202
+
waveform.play();
10203
+
});
10204
+
audioElement.addEventListener('play', function () {
10205
+
waveform.play();
10206
+
});
10207
+
audioElement.addEventListener('pause', function () {
10208
+
waveform.pause();
10209
+
});
10210
+
}
10211
+
else
10212
+
{
10213
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10214
+
}
10215
+
audioElement.play();
10216
+
aiomaticRmLoading(chatbut, instance);
10217
+
aiomatic_generator_working = false;
10218
+
}
10219
+
}
10220
+
fr.readAsText(blob);
10221
+
}
10222
+
speechRequest.send(speechData);
10223
+
}
10224
+
}
10225
+
else
10226
+
{
10227
+
if(aiomatic_chat_ajax_object.text_speech == 'google')
10228
+
{
10229
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
10230
+
response_data = aiomatic_stripHtmlTags(response_data);
10231
+
if(response_data != '')
10232
+
{
10233
+
has_speech = true;
10234
+
let speechData = new FormData();
10235
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
10236
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
10237
+
speechData.append('x_input_text', response_data);
10238
+
speechData.append('action', 'aiomatic_get_google_voice_chat');
10239
+
var speechRequest = new XMLHttpRequest();
10240
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
10241
+
speechRequest.ontimeout = () => {
10242
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
10243
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10244
+
aiomaticRmLoading(chatbut, instance);
10245
+
aiomatic_generator_working = false;
10246
+
};
10247
+
speechRequest.onerror = function ()
10248
+
{
10249
+
console.error("Network Error");
10250
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10251
+
aiomaticRmLoading(chatbut, instance);
10252
+
aiomatic_generator_working = false;
10253
+
};
10254
+
speechRequest.onabort = function ()
10255
+
{
10256
+
console.error("The request was aborted.");
10257
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10258
+
aiomaticRmLoading(chatbut, instance);
10259
+
aiomatic_generator_working = false;
10260
+
};
10261
+
speechRequest.onload = function () {
10262
+
var result = speechRequest.responseText;
10263
+
try {
10264
+
var jsonresult = JSON.parse(result);
10265
+
if(jsonresult.status === 'success'){
10266
+
var byteCharacters = atob(jsonresult.audio);
10267
+
const byteNumbers = new Array(byteCharacters.length);
10268
+
for (let i = 0; i < byteCharacters.length; i++) {
10269
+
byteNumbers[i] = byteCharacters.charCodeAt(i);
10270
+
}
10271
+
const byteArray = new Uint8Array(byteNumbers);
10272
+
const blob = new Blob([byteArray], {type: 'audio/mp3'});
10273
+
var blobUrl = URL.createObjectURL(blob);
10274
+
var audioElement = document.createElement('audio');
10275
+
audioElement.src = blobUrl;
10276
+
audioElement.controls = true;
10277
+
audioElement.style.marginTop = "2px";
10278
+
audioElement.style.width = "100%";
10279
+
audioElement.id = 'audio-element-' + instance;
10280
+
audioElement.addEventListener("error", function(event) {
10281
+
console.error("Error loading or playing the audio: ", event);
10282
+
});
10283
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
10284
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
10285
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
10286
+
{
10287
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
10288
+
var waveform = WaveSurfer.create({
10289
+
container: '#waveform-container' + instance,
10290
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
10291
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
10292
+
backend: 'MediaElement',
10293
+
height: 60,
10294
+
barWidth: 2,
10295
+
responsive: true, mediaControls: false, interact: false
10296
+
});
10297
+
waveform.setMuted(true);
10298
+
waveform.load(blobUrl);
10299
+
waveform.on('ready', function () {
10300
+
waveform.play();
10301
+
});
10302
+
audioElement.addEventListener('play', function () {
10303
+
waveform.play();
10304
+
});
10305
+
audioElement.addEventListener('pause', function () {
10306
+
waveform.pause();
10307
+
});
10308
+
}
10309
+
else
10310
+
{
10311
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10312
+
}
10313
+
audioElement.play();
10314
+
aiomaticRmLoading(chatbut, instance);
10315
+
aiomatic_generator_working = false;
10316
+
}
10317
+
else{
10318
+
var errorMessageDetail = 'Google: ' + jsonresult.msg;
10319
+
console.log('Google Text-to-Speech error: ' + errorMessageDetail);
10320
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10321
+
aiomaticRmLoading(chatbut, instance);
10322
+
aiomatic_generator_working = false;
10323
+
}
10324
+
}
10325
+
catch (errorSpeech){
10326
+
console.log('Exception in Google Text-to-Speech API: ' + errorSpeech);
10327
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10328
+
aiomaticRmLoading(chatbut, instance);
10329
+
aiomatic_generator_working = false;
10330
+
}
10331
+
}
10332
+
speechRequest.send(speechData);
10333
+
}
10334
+
}
10335
+
else
10336
+
{
10337
+
if(aiomatic_chat_ajax_object.text_speech == 'did')
10338
+
{
10339
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
10340
+
response_data = aiomatic_stripHtmlTags(response_data);
10341
+
if(response_data != '')
10342
+
{
10343
+
has_speech = true;
10344
+
let speechData = new FormData();
10345
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
10346
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
10347
+
speechData.append('x_input_text', response_data);
10348
+
speechData.append('action', 'aiomatic_get_d_id_video_chat');
10349
+
var speechRequest = new XMLHttpRequest();
10350
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
10351
+
speechRequest.ontimeout = () => {
10352
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
10353
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10354
+
aiomaticRmLoading(chatbut, instance);
10355
+
aiomatic_generator_working = false;
10356
+
};
10357
+
speechRequest.onerror = function ()
10358
+
{
10359
+
console.error("Network Error");
10360
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10361
+
aiomaticRmLoading(chatbut, instance);
10362
+
aiomatic_generator_working = false;
10363
+
};
10364
+
speechRequest.onabort = function ()
10365
+
{
10366
+
console.error("The request was aborted.");
10367
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10368
+
aiomaticRmLoading(chatbut, instance);
10369
+
aiomatic_generator_working = false;
10370
+
};
10371
+
speechRequest.onload = function () {
10372
+
var result = speechRequest.responseText;
10373
+
try
10374
+
{
10375
+
var jsonresult = JSON.parse(result);
10376
+
if(jsonresult.status === 'success')
10377
+
{
10378
+
var videoURL = '<video class="ai_video" autoplay="autoplay" controls="controls"><source src="' + jsonresult.video + '" type="video/mp4"></video>';
10379
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-video">' + videoURL + '</div>');
10380
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10381
+
aiomaticRmLoading(chatbut, instance);
10382
+
aiomatic_generator_working = false;
10383
+
}
10384
+
else
10385
+
{
10386
+
var errorMessageDetail = 'D-ID: ' + jsonresult.msg;
10387
+
console.log('D-ID Text-to-video error: ' + errorMessageDetail);
10388
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10389
+
aiomaticRmLoading(chatbut, instance);
10390
+
aiomatic_generator_working = false;
10391
+
}
10392
+
}
10393
+
catch (errorSpeech){
10394
+
console.log('Exception in D-ID Text-to-video API: ' + errorSpeech);
10395
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10396
+
aiomaticRmLoading(chatbut, instance);
10397
+
aiomatic_generator_working = false;
10398
+
}
10399
+
}
10400
+
speechRequest.send(speechData);
10401
+
}
10402
+
}
10403
+
else
10404
+
{
10405
+
if(aiomatic_chat_ajax_object.text_speech == 'didstream')
10406
+
{
10407
+
if(avatarImageUrl != '' && did_app_id != '')
10408
+
{
10409
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
10410
+
response_data = aiomatic_stripHtmlTags(response_data);
10411
+
if(response_data != '')
10412
+
{
10413
+
if(streamingEpicFail === false)
10414
+
{
10415
+
has_speech = true;
10416
+
myStreamObject.talkToDidStream(response_data);
10417
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10418
+
aiomatic_generator_working = false;
10419
+
}
10420
+
}
10421
+
}
10422
+
}
10423
+
else
10424
+
{
10425
+
if(aiomatic_chat_ajax_object.text_speech == 'azure')
10426
+
{
10427
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
10428
+
response_data = aiomatic_stripHtmlTags(response_data);
10429
+
if(response_data != '')
10430
+
{
10431
+
if(azure_speech_id != '')
10432
+
{
10433
+
if(streamingEpicFail === false)
10434
+
{
10435
+
has_speech = true;
10436
+
var ttsvoice = aiomatic_chat_ajax_object.azure_voice;
10437
+
var personalVoiceSpeakerProfileID = aiomatic_chat_ajax_object.azure_voice_profile;
10438
+
aiomaticRmLoading(chatbut, instance);
10439
+
azureSpeakText(response_data, ttsvoice, personalVoiceSpeakerProfileID);
10440
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10441
+
aiomatic_generator_working = false;
10442
+
}
10443
+
}
10444
+
}
10445
+
}
10446
+
else
10447
+
{
10448
+
if(aiomatic_chat_ajax_object.text_speech == 'free')
10449
+
{
10450
+
var T2S;
10451
+
if("speechSynthesis" in window || speechSynthesis)
10452
+
{
10453
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
10454
+
response_data = aiomatic_stripHtmlTags(response_data);
10455
+
if(response_data != '')
10456
+
{
10457
+
T2S = window.speechSynthesis || speechSynthesis;
10458
+
var utter = new SpeechSynthesisUtterance(response_data);
10459
+
var voiceSetting = aiomatic_chat_ajax_object.free_voice.split(";");
10460
+
var desiredVoiceName = voiceSetting[0].trim();
10461
+
var desiredLang = voiceSetting[1].trim();
10462
+
var voices = T2S.getVoices();
10463
+
var selectedVoice = voices.find(function(voice) {
10464
+
return voice.name === desiredVoiceName && voice.lang === desiredLang;
10465
+
});
10466
+
if (selectedVoice) {
10467
+
utter.voice = selectedVoice;
10468
+
utter.lang = selectedVoice.lang;
10469
+
}
10470
+
else
10471
+
{
10472
+
utter.lang = desiredLang;
10473
+
}
10474
+
T2S.speak(utter);
10475
+
}
10476
+
}
10477
+
}
10478
+
}
10479
+
}
10480
+
}
10481
+
}
10482
+
}
10483
+
}
10484
+
}
10485
+
if(has_speech === false)
10486
+
{
10487
+
if(error_generated == '')
10488
+
{
10489
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10490
+
}
10491
+
aiomaticRmLoading(chatbut, instance);
10492
+
aiomatic_generator_working = false;
10493
+
}
10494
+
}
10495
+
}
10496
+
else
10497
+
{
10498
+
var aiomatic_newline_before = false;
10499
+
var aiomatic_response_events = 0;
10500
+
var aiomatic_limitLines = 1;
10501
+
var currentContent = jQuery('#aiomatic_chat_history' + instance).html();
10502
+
var resultData = null;
10503
+
if(e.data == '[DONE]')
10504
+
{
10505
+
var hasFinishReason = true;
10506
+
}
10507
+
else
10508
+
{
10509
+
try
10510
+
{
10511
+
resultData = JSON.parse(e.data);
10512
+
}
10513
+
catch (e)
10514
+
{
10515
+
console.warn(e);
10516
+
aiomaticRmLoading(chatbut, instance);
10517
+
aiomatic_generator_working = false;
10518
+
eventGenerator.close();
10519
+
jQuery('#aistopbut' + instance).hide();
10520
+
return;
10521
+
}
10522
+
var hasFinishReason = resultData &&
10523
+
(resultData.finish_reason === "stop" ||
10524
+
resultData.finish_reason === "length");
10525
+
if(resultData.stop_reason == 'stop_sequence' || resultData.stop_reason == 'max_tokens')
10526
+
{
10527
+
hasFinishReason = true;
10528
+
}
10529
+
}
10530
+
var content_generated = '';
10531
+
if(hasFinishReason){
10532
+
count_line += 1;
10533
+
aiomatic_response_events = 0;
10534
+
}
10535
+
else
10536
+
{
10537
+
if(resultData !== null)
10538
+
{
10539
+
var result = resultData;
10540
+
}
10541
+
else
10542
+
{
10543
+
var result = null;
10544
+
try {
10545
+
result = JSON.parse(e.data);
10546
+
}
10547
+
catch (e)
10548
+
{
10549
+
console.warn(e);
10550
+
aiomaticRmLoading(chatbut, instance);
10551
+
aiomatic_generator_working = false;
10552
+
jQuery('#aistopbut' + instance).hide();
10553
+
eventGenerator.close();
10554
+
return;
10555
+
};
10556
+
}
10557
+
if(result.error !== undefined){
10558
+
if(result.error !== undefined){
10559
+
error_generated = result.error[0].message;
10560
+
}
10561
+
else
10562
+
{
10563
+
error_generated = JSON.stringify(result.error);
10564
+
}
10565
+
if(error_generated === undefined)
10566
+
{
10567
+
error_generated = result.error.message;
10568
+
}
10569
+
if(error_generated === undefined)
10570
+
{
10571
+
error_generated = result.error;
10572
+
}
10573
+
console.log('Error while processing request(1): ' + error_generated);
10574
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + error_generated + '</div>');
10575
+
}
10576
+
else
10577
+
{
10578
+
if(result && result.completion && result.completion !== undefined)
10579
+
{
10580
+
content_generated = result.completion;
10581
+
}
10582
+
else if(result && result.delta && result.delta.text && result.delta.text !== undefined)
10583
+
{
10584
+
content_generated = result.delta.text;
10585
+
}
10586
+
else if(result && result.choices && result.choices[0] && result.choices[0].finish_reason && result.choices[0].finish_reason === 'stop')
10587
+
{
10588
+
hasFinishReason = true;
10589
+
count_line += 1;
10590
+
aiomatic_response_events = 0;
10591
+
}
10592
+
else
10593
+
{
10594
+
console.log('Unrecognized format: ' + JSON.stringify(result));
10595
+
content_generated = '';
10596
+
}
10597
+
}
10598
+
if(aiomatic_chat_ajax_object.enable_html != true)
10599
+
{
10600
+
content_generated = aiomatic_esc_html(content_generated);
10601
+
}
10602
+
response_data += aiomatic_nl2br(content_generated);
10603
+
if(aiomatic_chat_ajax_object.strip_js == true)
10604
+
{
10605
+
response_data = response_data.replace(/<script[\s\S]*?<\/script>/gi, '');
10606
+
response_data = response_data.replace(/on\w+="[^"]*"/gi, '');
10607
+
}
10608
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
10609
+
response_data = processKatexMarkdown(response_data);
10610
+
}
10611
+
if(aiomatic_chat_ajax_object.markdown_parse == 'on')
10612
+
{
10613
+
response_data = aiomatic_parseMarkdown(response_data);
10614
+
}
10615
+
var appendx = '<div class="ai-wrapper">';
10616
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
10617
+
{
10618
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
10619
+
}
10620
+
appendx += '<div class="ai-bubble ai-other">' + response_data + '</div>';
10621
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
10622
+
{
10623
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
10624
+
}
10625
+
appendx += '</div>';
10626
+
if((content_generated === '\n' || content_generated === ' \n' || content_generated === '.\n' || content_generated === '\n\n' || content_generated === '.\n\n' || content_generated === '"\n') && aiomatic_response_events > 0 && currentContent !== ''){
10627
+
if(!aiomatic_newline_before) {
10628
+
aiomatic_newline_before = true;
10629
+
jQuery('#aiomatic_chat_history' + instance).html(currentContent + '<br /><br />');
10630
+
}
10631
+
}
10632
+
else if(content_generated === '\n' && aiomatic_response_events === 0 && currentContent === ''){
10633
+
}
10634
+
else
10635
+
{
10636
+
aiomatic_newline_before = false;
10637
+
aiomatic_response_events += 1;
10638
+
jQuery('#aiomatic_chat_history' + instance).html(initialContent + appendx);
10639
+
}
10640
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
10641
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
10642
+
renderMathInElement(katexContainer, {
10643
+
delimiters: [
10644
+
10645
+
{ left: '\\(', right: '\\)', display: false },
10646
+
{ left: '\\[', right: '\\]', display: true }
10647
+
],
10648
+
throwOnError: false
10649
+
});
10650
+
}
10651
+
}
10652
+
if(count_line >= aiomatic_limitLines)
10653
+
{
10654
+
eventGenerator.close();
10655
+
jQuery('#aistopbut' + instance).hide();
10656
+
var x_input_text = jQuery('#aiomatic_chat_history' + instance).html();
10657
+
if((persistent != 'off' && persistent != '0' && persistent != '') && user_id != '0' && error_generated == '')
10658
+
{
10659
+
var save_persistent = x_input_text;
10660
+
if(persistent == 'vector')
10661
+
{
10662
+
save_persistent = user_question;
10663
+
}
10664
+
var saving_index = '';
10665
+
var main_index = '';
10666
+
if(persistent == 'history')
10667
+
{
10668
+
saving_index = jQuery('#chat-log-identifier' + instance).val();
10669
+
main_index = jQuery('#chat-main-identifier' + instance).val();
10670
+
}
10671
+
jQuery.ajax({
10672
+
type: 'POST',
10673
+
url: aiomatic_chat_ajax_object.ajax_url,
10674
+
data: {
10675
+
action: 'aiomatic_user_meta_save',
10676
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
10677
+
persistent: persistent,
10678
+
thread_id: aiomatic_chat_ajax_object.thread_id,
10679
+
x_input_text: save_persistent,
10680
+
user_id: user_id,
10681
+
saving_index: saving_index,
10682
+
main_index: main_index
10683
+
},
10684
+
success: function(result) {
10685
+
if(result.name && result.msg)
10686
+
{
10687
+
var logsdrop = jQuery('#chat-logs-dropdown' + instance);
10688
+
if(logsdrop)
10689
+
{
10690
+
var newChatLogItem = jQuery('<div class="chat-log-item" id="chat-log-item' + saving_index + '" data-id="' + saving_index + '" onclick="aiomatic_trigger_chat_logs(\'' + saving_index + '\', \'' + instance + '\')">' + result.name + '<span onclick="aiomatic_remove_chat_logs(event, \'' + saving_index + '\', \'' + instance + '\');" class="aiomatic-remove-item">X</span></div>');
10691
+
var chatLogNew = logsdrop.find('.chat-log-new');
10692
+
if (chatLogNew.length)
10693
+
{
10694
+
var nextSibling = chatLogNew.next();
10695
+
if (nextSibling.length && nextSibling.hasClass('date-group-label'))
10696
+
{
10697
+
newChatLogItem.insertAfter(nextSibling);
10698
+
}
10699
+
else
10700
+
{
10701
+
newChatLogItem.insertAfter(chatLogNew);
10702
+
}
10703
+
}
10704
+
else
10705
+
{
10706
+
logsdrop.append(newChatLogItem);
10707
+
}
10708
+
}
10709
+
}
10710
+
},
10711
+
error: function(error) {
10712
+
console.log('Error while saving persistent user log: ' + error.responseText);
10713
+
},
10714
+
});
10715
+
}
10716
+
if(error_generated == '')
10717
+
{
10718
+
jQuery.ajax({
10719
+
type: 'POST',
10720
+
url: aiomatic_chat_ajax_object.ajax_url,
10721
+
data: {
10722
+
action: 'aiomatic_record_user_usage',
10723
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
10724
+
user_id: user_id,
10725
+
input_text: input_text,
10726
+
response_text: response_data,
10727
+
model: model,
10728
+
temp: temp,
10729
+
vision_file: vision_file,
10730
+
user_token_cap_per_day: aiomatic_chat_ajax_object.user_token_cap_per_day,
10731
+
source: 'chat'
10732
+
},
10733
+
success: function()
10734
+
{
10735
+
},
10736
+
error: function(error) {
10737
+
console.log('Error while saving user data: ' + error.responseText);
10738
+
},
10739
+
});
10740
+
}
10741
+
if(error_generated == '')
10742
+
{
10743
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10744
+
}
10745
+
var has_speech = false;
10746
+
if(aiomatic_chat_ajax_object.receive_message_sound != '')
10747
+
{
10748
+
var snd = new Audio(aiomatic_chat_ajax_object.receive_message_sound);
10749
+
snd.play();
10750
+
}
10751
+
if(error_generated == '' && !jQuery('.aiomatic-gg-unmute').length)
10752
+
{
10753
+
if(aiomatic_chat_ajax_object.text_speech == 'elevenlabs')
10754
+
{
10755
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
10756
+
response_data = aiomatic_stripHtmlTags(response_data);
10757
+
if(response_data != '')
10758
+
{
10759
+
has_speech = true;
10760
+
let speechData = new FormData();
10761
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
10762
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
10763
+
speechData.append('x_input_text', response_data);
10764
+
speechData.append('action', 'aiomatic_get_elevenlabs_voice_chat');
10765
+
var speechRequest = new XMLHttpRequest();
10766
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
10767
+
speechRequest.responseType = "arraybuffer";
10768
+
speechRequest.ontimeout = () => {
10769
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
10770
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10771
+
aiomaticRmLoading(chatbut, instance);
10772
+
aiomatic_generator_working = false;
10773
+
};
10774
+
speechRequest.onerror = function ()
10775
+
{
10776
+
console.error("Network Error");
10777
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10778
+
aiomaticRmLoading(chatbut, instance);
10779
+
aiomatic_generator_working = false;
10780
+
};
10781
+
speechRequest.onabort = function ()
10782
+
{
10783
+
console.error("The request was aborted.");
10784
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10785
+
aiomaticRmLoading(chatbut, instance);
10786
+
aiomatic_generator_working = false;
10787
+
};
10788
+
speechRequest.onload = function () {
10789
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
10790
+
var fr = new FileReader();
10791
+
fr.onload = function () {
10792
+
var fileText = this.result;
10793
+
try {
10794
+
var errorMessage = JSON.parse(fileText);
10795
+
console.log('ElevenLabs API failed: ' + errorMessage.msg);
10796
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10797
+
aiomaticRmLoading(chatbut, instance);
10798
+
aiomatic_generator_working = false;
10799
+
} catch (errorBlob) {
10800
+
var blobUrl = URL.createObjectURL(blob);
10801
+
var audioElement = document.createElement('audio');
10802
+
audioElement.src = blobUrl;
10803
+
audioElement.controls = true;
10804
+
audioElement.style.marginTop = "2px";
10805
+
audioElement.style.width = "100%";
10806
+
audioElement.id = 'audio-element-' + instance;
10807
+
audioElement.addEventListener("error", function(event) {
10808
+
console.error("Error loading or playing the audio: ", event);
10809
+
});
10810
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
10811
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
10812
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
10813
+
{
10814
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
10815
+
var waveform = WaveSurfer.create({
10816
+
container: '#waveform-container' + instance,
10817
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
10818
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
10819
+
backend: 'MediaElement',
10820
+
height: 60,
10821
+
barWidth: 2,
10822
+
responsive: true, mediaControls: false, interact: false
10823
+
});
10824
+
waveform.setMuted(true);
10825
+
waveform.load(blobUrl);
10826
+
waveform.on('ready', function () {
10827
+
waveform.play();
10828
+
});
10829
+
audioElement.addEventListener('play', function () {
10830
+
waveform.play();
10831
+
});
10832
+
audioElement.addEventListener('pause', function () {
10833
+
waveform.pause();
10834
+
});
10835
+
}
10836
+
else
10837
+
{
10838
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10839
+
}
10840
+
audioElement.play();
10841
+
aiomaticRmLoading(chatbut, instance);
10842
+
aiomatic_generator_working = false;
10843
+
}
10844
+
}
10845
+
fr.readAsText(blob);
10846
+
}
10847
+
speechRequest.send(speechData);
10848
+
}
10849
+
}
10850
+
else
10851
+
{
10852
+
if(aiomatic_chat_ajax_object.text_speech == 'openai')
10853
+
{
10854
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
10855
+
response_data = aiomatic_stripHtmlTags(response_data);
10856
+
if(response_data != '')
10857
+
{
10858
+
has_speech = true;
10859
+
let speechData = new FormData();
10860
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
10861
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
10862
+
speechData.append('x_input_text', response_data);
10863
+
speechData.append('action', 'aiomatic_get_openai_voice_chat');
10864
+
var speechRequest = new XMLHttpRequest();
10865
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
10866
+
speechRequest.responseType = "arraybuffer";
10867
+
speechRequest.ontimeout = () => {
10868
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
10869
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10870
+
aiomaticRmLoading(chatbut, instance);
10871
+
aiomatic_generator_working = false;
10872
+
};
10873
+
speechRequest.onerror = function ()
10874
+
{
10875
+
console.error("Network Error");
10876
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10877
+
aiomaticRmLoading(chatbut, instance);
10878
+
aiomatic_generator_working = false;
10879
+
};
10880
+
speechRequest.onabort = function ()
10881
+
{
10882
+
console.error("The request was aborted.");
10883
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10884
+
aiomaticRmLoading(chatbut, instance);
10885
+
aiomatic_generator_working = false;
10886
+
};
10887
+
speechRequest.onload = function () {
10888
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
10889
+
var fr = new FileReader();
10890
+
fr.onload = function () {
10891
+
var fileText = this.result;
10892
+
try {
10893
+
var errorMessage = JSON.parse(fileText);
10894
+
console.log('OpenAI TTS API failed: ' + errorMessage.msg);
10895
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10896
+
aiomaticRmLoading(chatbut, instance);
10897
+
aiomatic_generator_working = false;
10898
+
} catch (errorBlob) {
10899
+
var blobUrl = URL.createObjectURL(blob);
10900
+
var audioElement = document.createElement('audio');
10901
+
audioElement.src = blobUrl;
10902
+
audioElement.controls = true;
10903
+
audioElement.style.marginTop = "2px";
10904
+
audioElement.style.width = "100%";
10905
+
audioElement.id = 'audio-element-' + instance;
10906
+
audioElement.addEventListener("error", function(event) {
10907
+
console.error("Error loading or playing the audio: ", event);
10908
+
});
10909
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
10910
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
10911
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
10912
+
{
10913
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
10914
+
var waveform = WaveSurfer.create({
10915
+
container: '#waveform-container' + instance,
10916
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
10917
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
10918
+
backend: 'MediaElement',
10919
+
height: 60,
10920
+
barWidth: 2,
10921
+
responsive: true, mediaControls: false, interact: false
10922
+
});
10923
+
waveform.setMuted(true);
10924
+
waveform.load(blobUrl);
10925
+
waveform.on('ready', function () {
10926
+
waveform.play();
10927
+
});
10928
+
audioElement.addEventListener('play', function () {
10929
+
waveform.play();
10930
+
});
10931
+
audioElement.addEventListener('pause', function () {
10932
+
waveform.pause();
10933
+
});
10934
+
}
10935
+
else
10936
+
{
10937
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10938
+
}
10939
+
audioElement.play();
10940
+
aiomaticRmLoading(chatbut, instance);
10941
+
aiomatic_generator_working = false;
10942
+
}
10943
+
}
10944
+
fr.readAsText(blob);
10945
+
}
10946
+
speechRequest.send(speechData);
10947
+
}
10948
+
}
10949
+
else
10950
+
{
10951
+
if(aiomatic_chat_ajax_object.text_speech == 'google')
10952
+
{
10953
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
10954
+
response_data = aiomatic_stripHtmlTags(response_data);
10955
+
if(response_data != '')
10956
+
{
10957
+
has_speech = true;
10958
+
let speechData = new FormData();
10959
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
10960
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
10961
+
speechData.append('x_input_text', response_data);
10962
+
speechData.append('action', 'aiomatic_get_google_voice_chat');
10963
+
var speechRequest = new XMLHttpRequest();
10964
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
10965
+
speechRequest.ontimeout = () => {
10966
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
10967
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10968
+
aiomaticRmLoading(chatbut, instance);
10969
+
aiomatic_generator_working = false;
10970
+
};
10971
+
speechRequest.onerror = function ()
10972
+
{
10973
+
console.error("Network Error");
10974
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10975
+
aiomaticRmLoading(chatbut, instance);
10976
+
aiomatic_generator_working = false;
10977
+
};
10978
+
speechRequest.onabort = function ()
10979
+
{
10980
+
console.error("The request was aborted.");
10981
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
10982
+
aiomaticRmLoading(chatbut, instance);
10983
+
aiomatic_generator_working = false;
10984
+
};
10985
+
speechRequest.onload = function () {
10986
+
var result = speechRequest.responseText;
10987
+
try {
10988
+
var jsonresult = JSON.parse(result);
10989
+
if(jsonresult.status === 'success'){
10990
+
var byteCharacters = atob(jsonresult.audio);
10991
+
const byteNumbers = new Array(byteCharacters.length);
10992
+
for (let i = 0; i < byteCharacters.length; i++) {
10993
+
byteNumbers[i] = byteCharacters.charCodeAt(i);
10994
+
}
10995
+
const byteArray = new Uint8Array(byteNumbers);
10996
+
const blob = new Blob([byteArray], {type: 'audio/mp3'});
10997
+
var blobUrl = URL.createObjectURL(blob);
10998
+
var audioElement = document.createElement('audio');
10999
+
audioElement.src = blobUrl;
11000
+
audioElement.controls = true;
11001
+
audioElement.style.marginTop = "2px";
11002
+
audioElement.style.width = "100%";
11003
+
audioElement.id = 'audio-element-' + instance;
11004
+
audioElement.addEventListener("error", function(event) {
11005
+
console.error("Error loading or playing the audio: ", event);
11006
+
});
11007
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
11008
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
11009
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
11010
+
{
11011
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
11012
+
var waveform = WaveSurfer.create({
11013
+
container: '#waveform-container' + instance,
11014
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
11015
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
11016
+
backend: 'MediaElement',
11017
+
height: 60,
11018
+
barWidth: 2,
11019
+
responsive: true, mediaControls: false, interact: false
11020
+
});
11021
+
waveform.setMuted(true);
11022
+
waveform.load(blobUrl);
11023
+
waveform.on('ready', function () {
11024
+
waveform.play();
11025
+
});
11026
+
audioElement.addEventListener('play', function () {
11027
+
waveform.play();
11028
+
});
11029
+
audioElement.addEventListener('pause', function () {
11030
+
waveform.pause();
11031
+
});
11032
+
}
11033
+
else
11034
+
{
11035
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11036
+
}
11037
+
audioElement.play();
11038
+
aiomaticRmLoading(chatbut, instance);
11039
+
aiomatic_generator_working = false;
11040
+
}
11041
+
else{
11042
+
var errorMessageDetail = 'Google: ' + jsonresult.msg;
11043
+
console.log('Google Text-to-Speech error: ' + errorMessageDetail);
11044
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11045
+
aiomaticRmLoading(chatbut, instance);
11046
+
aiomatic_generator_working = false;
11047
+
}
11048
+
}
11049
+
catch (errorSpeech){
11050
+
console.log('Exception in Google Text-to-Speech API: ' + errorSpeech);
11051
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11052
+
aiomaticRmLoading(chatbut, instance);
11053
+
aiomatic_generator_working = false;
11054
+
}
11055
+
}
11056
+
speechRequest.send(speechData);
11057
+
}
11058
+
}
11059
+
else
11060
+
{
11061
+
if(aiomatic_chat_ajax_object.text_speech == 'did')
11062
+
{
11063
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
11064
+
response_data = aiomatic_stripHtmlTags(response_data);
11065
+
if(response_data != '')
11066
+
{
11067
+
has_speech = true;
11068
+
let speechData = new FormData();
11069
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
11070
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
11071
+
speechData.append('x_input_text', response_data);
11072
+
speechData.append('action', 'aiomatic_get_d_id_video_chat');
11073
+
var speechRequest = new XMLHttpRequest();
11074
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
11075
+
speechRequest.ontimeout = () => {
11076
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
11077
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11078
+
aiomaticRmLoading(chatbut, instance);
11079
+
aiomatic_generator_working = false;
11080
+
};
11081
+
speechRequest.onerror = function ()
11082
+
{
11083
+
console.error("Network Error");
11084
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11085
+
aiomaticRmLoading(chatbut, instance);
11086
+
aiomatic_generator_working = false;
11087
+
};
11088
+
speechRequest.onabort = function ()
11089
+
{
11090
+
console.error("The request was aborted.");
11091
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11092
+
aiomaticRmLoading(chatbut, instance);
11093
+
aiomatic_generator_working = false;
11094
+
};
11095
+
speechRequest.onload = function () {
11096
+
var result = speechRequest.responseText;
11097
+
try
11098
+
{
11099
+
var jsonresult = JSON.parse(result);
11100
+
if(jsonresult.status === 'success')
11101
+
{
11102
+
var videoURL = '<video class="ai_video" autoplay="autoplay" controls="controls"><source src="' + jsonresult.video + '" type="video/mp4"></video>';
11103
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-video">' + videoURL + '</div>');
11104
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11105
+
aiomaticRmLoading(chatbut, instance);
11106
+
aiomatic_generator_working = false;
11107
+
}
11108
+
else
11109
+
{
11110
+
var errorMessageDetail = 'D-ID: ' + jsonresult.msg;
11111
+
console.log('D-ID Text-to-video error: ' + errorMessageDetail);
11112
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11113
+
aiomaticRmLoading(chatbut, instance);
11114
+
aiomatic_generator_working = false;
11115
+
}
11116
+
}
11117
+
catch (errorSpeech){
11118
+
console.log('Exception in D-ID Text-to-video API: ' + errorSpeech);
11119
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11120
+
aiomaticRmLoading(chatbut, instance);
11121
+
aiomatic_generator_working = false;
11122
+
}
11123
+
}
11124
+
speechRequest.send(speechData);
11125
+
}
11126
+
}
11127
+
else
11128
+
{
11129
+
if(aiomatic_chat_ajax_object.text_speech == 'didstream')
11130
+
{
11131
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
11132
+
response_data = aiomatic_stripHtmlTags(response_data);
11133
+
if(response_data != '')
11134
+
{
11135
+
if(avatarImageUrl != '' && did_app_id != '')
11136
+
{
11137
+
if(streamingEpicFail === false)
11138
+
{
11139
+
has_speech = true;
11140
+
myStreamObject.talkToDidStream(response_data);
11141
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11142
+
aiomatic_generator_working = false;
11143
+
}
11144
+
}
11145
+
}
11146
+
}
11147
+
else
11148
+
{
11149
+
if(aiomatic_chat_ajax_object.text_speech == 'azure')
11150
+
{
11151
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
11152
+
response_data = aiomatic_stripHtmlTags(response_data);
11153
+
if(response_data != '')
11154
+
{
11155
+
if(azure_speech_id != '')
11156
+
{
11157
+
if(streamingEpicFail === false)
11158
+
{
11159
+
has_speech = true;
11160
+
var ttsvoice = aiomatic_chat_ajax_object.azure_voice;
11161
+
var personalVoiceSpeakerProfileID = aiomatic_chat_ajax_object.azure_voice_profile;
11162
+
aiomaticRmLoading(chatbut, instance);
11163
+
azureSpeakText(response_data, ttsvoice, personalVoiceSpeakerProfileID);
11164
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11165
+
aiomatic_generator_working = false;
11166
+
}
11167
+
}
11168
+
}
11169
+
}
11170
+
else
11171
+
{
11172
+
if(aiomatic_chat_ajax_object.text_speech == 'free')
11173
+
{
11174
+
var T2S;
11175
+
if("speechSynthesis" in window || speechSynthesis)
11176
+
{
11177
+
response_data = response_data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
11178
+
response_data = aiomatic_stripHtmlTags(response_data);
11179
+
if(response_data != '')
11180
+
{
11181
+
T2S = window.speechSynthesis || speechSynthesis;
11182
+
var utter = new SpeechSynthesisUtterance(response_data);
11183
+
var voiceSetting = aiomatic_chat_ajax_object.free_voice.split(";");
11184
+
var desiredVoiceName = voiceSetting[0].trim();
11185
+
var desiredLang = voiceSetting[1].trim();
11186
+
var voices = T2S.getVoices();
11187
+
var selectedVoice = voices.find(function(voice) {
11188
+
return voice.name === desiredVoiceName && voice.lang === desiredLang;
11189
+
});
11190
+
if (selectedVoice) {
11191
+
utter.voice = selectedVoice;
11192
+
utter.lang = selectedVoice.lang;
11193
+
}
11194
+
else
11195
+
{
11196
+
utter.lang = desiredLang;
11197
+
}
11198
+
T2S.speak(utter);
11199
+
}
11200
+
}
11201
+
}
11202
+
}
11203
+
}
11204
+
}
11205
+
}
11206
+
}
11207
+
}
11208
+
}
11209
+
if(has_speech === false)
11210
+
{
11211
+
if(error_generated == '')
11212
+
{
11213
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11214
+
}
11215
+
aiomaticRmLoading(chatbut, instance);
11216
+
aiomatic_generator_working = false;
11217
+
}
11218
+
}
11219
+
}
11220
+
};
11221
+
eventGenerator.onerror = handleErrorEvent;
11222
+
function handleErrorEvent(e)
11223
+
{
11224
+
console.log('Halting execution, EventGenerator error: ' + JSON.stringify(e));
11225
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
11226
+
aiomaticRmLoading(chatbut, instance);
11227
+
aiomatic_generator_working = false;
11228
+
eventGenerator.close();
11229
+
jQuery('#aistopbut' + instance).hide();
11230
+
};
11231
+
function handleErrorEvent1(e)
11232
+
{
11233
+
console.log('Halting execution, EventGenerator1 error: ' + JSON.stringify(e));
11234
+
11235
+
if (eventGenerator.readyState === EventSource.CLOSED) {
11236
+
console.error('EventSource connection was closed.');
11237
+
} else if (eventGenerator.readyState === EventSource.CONNECTING) {
11238
+
console.warn('EventSource is trying to reconnect...');
11239
+
}
11240
+
11241
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
11242
+
aiomaticRmLoading(chatbut, instance);
11243
+
aiomatic_generator_working = false;
11244
+
eventGenerator.close();
11245
+
jQuery('#aistopbut' + instance).hide();
11246
+
};
11247
+
function handleErrorEvent2(e)
11248
+
{
11249
+
console.log('Halting execution, EventGenerator2 error: ' + JSON.stringify(e));
11250
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
11251
+
aiomaticRmLoading(chatbut, instance);
11252
+
aiomatic_generator_working = false;
11253
+
eventGenerator.close();
11254
+
jQuery('#aistopbut' + instance).hide();
11255
+
};
11256
+
function handleErrorEvent3(e)
11257
+
{
11258
+
console.log('Halting execution, EventGenerator3 error: ' + JSON.stringify(e));
11259
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
11260
+
aiomaticRmLoading(chatbut, instance);
11261
+
aiomatic_generator_working = false;
11262
+
eventGenerator.close();
11263
+
jQuery('#aistopbut' + instance).hide();
11264
+
};
11265
+
function handleErrorEvent4(e)
11266
+
{
11267
+
console.log('Halting execution, EventGenerator4 error: ' + JSON.stringify(e));
11268
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
11269
+
aiomaticRmLoading(chatbut, instance);
11270
+
aiomatic_generator_working = false;
11271
+
eventGenerator.close();
11272
+
jQuery('#aistopbut' + instance).hide();
11273
+
};
11274
+
}
11275
+
else
11276
+
{
11277
+
var internet_permission = aiomatic_chat_ajax_object.internet_access;
11278
+
if(jQuery('#aiomatic-globe-overlay' + instance).hasClass('aiomatic-globe-bar') && jQuery('#aiomatic-globe-overlay' + instance).is(':visible'))
11279
+
{
11280
+
internet_permission = 'disabled';
11281
+
}
11282
+
if(aiomatic_chat_ajax_object.bots_data && aiomatic_chat_ajax_object.strip_botname == '1')
11283
+
{
11284
+
aiomatic_chat_ajax_object.bots_data.forEach((relement) => input_text = input_text.replace('@' + relement.name, ''));
11285
+
}
11286
+
jQuery.ajax({
11287
+
type: 'POST',
11288
+
url: aiomatic_chat_ajax_object.ajax_url,
11289
+
data: {
11290
+
action: 'aiomatic_chat_submit',
11291
+
input_text: input_text,
11292
+
nonce: aiomatic_chat_ajax_object.nonce,
11293
+
model: model,
11294
+
temp: temp,
11295
+
top_p: top_p,
11296
+
presence: presence,
11297
+
frequency: frequency,
11298
+
store_data: store_data,
11299
+
user_token_cap_per_day: user_token_cap_per_day,
11300
+
remember_string: remember_string,
11301
+
is_modern_gpt: is_modern_gpt,
11302
+
user_id: user_id,
11303
+
vision_file: vision_file,
11304
+
user_question: user_question,
11305
+
ai_assistant_id: ai_assistant_id,
11306
+
ai_thread_id: ai_thread_id,
11307
+
pdf_data: pdf_data,
11308
+
file_data: file_data,
11309
+
internet_access: internet_permission,
11310
+
embeddings: aiomatic_chat_ajax_object.embeddings,
11311
+
embeddings_namespace: aiomatic_chat_ajax_object.embeddings_namespace,
11312
+
enable_god_mode: enable_god_mode,
11313
+
user_lang: user_lang,
11314
+
mcp_servers: aiomatic_chat_ajax_object.mcp_servers
11315
+
},
11316
+
success: function(response) {
11317
+
if(typeof response === 'string' || response instanceof String)
11318
+
{
11319
+
try {
11320
+
var responset = JSON.parse(response);
11321
+
response = responset;
11322
+
} catch (error) {
11323
+
console.error("An error occurred while parsing the JSON: " + error + ' Json: ' + response);
11324
+
}
11325
+
}
11326
+
if(response.status == 'success')
11327
+
{
11328
+
if(response.thread_id !== undefined)
11329
+
{
11330
+
jQuery('#aiomatic_thread_id' + instance).val(response.thread_id);
11331
+
}
11332
+
if(response.data == '')
11333
+
{
11334
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.conversation_end + '</div>');
11335
+
}
11336
+
else
11337
+
{
11338
+
if(response.data == 'AiomaticConversationEnded~!@#$%^&*()')
11339
+
{
11340
+
const inputField = document.getElementById('aiomatic_chat_input' + instance);
11341
+
inputField.disabled = true;
11342
+
inputField.chatended = true;
11343
+
const speechButton = document.getElementById('openai-chat-speech-button' + instance);
11344
+
if (speechButton) {
11345
+
speechButton.disabled = true;
11346
+
}
11347
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.conversation_ended + '</div>');
11348
+
aiomaticRmLoading(chatbut, instance);
11349
+
return;
11350
+
}
11351
+
if(ai_message_preppend != '')
11352
+
{
11353
+
response.data = airemovePrefix(response.data.aitrim(), ai_message_preppend);
11354
+
response.data = response.data.aitrim();
11355
+
}
11356
+
if(user_message_preppend != '')
11357
+
{
11358
+
response.data = airemoveAfter(response.data.aitrim(), user_message_preppend);
11359
+
response.data = response.data.aitrim();
11360
+
}
11361
+
response.data = response.data.replace(/\n/g, '<br>');
11362
+
var x_input_text = jQuery('#aiomatic_chat_history' + instance).html();
11363
+
if((persistent != 'off' && persistent != '0' && persistent != '') && user_id != '0')
11364
+
{
11365
+
if(response.thread_id !== undefined)
11366
+
{
11367
+
var threadid = response.thread_id;
11368
+
}
11369
+
else
11370
+
{
11371
+
var threadid = aiomatic_chat_ajax_object.thread_id;
11372
+
}
11373
+
var save_persistent = x_input_text;
11374
+
if(persistent == 'vector')
11375
+
{
11376
+
save_persistent = user_question;
11377
+
}
11378
+
var appendx = '<div class="ai-wrapper">';
11379
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
11380
+
{
11381
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
11382
+
}
11383
+
appendx += '<div class="ai-bubble ai-other">' + response.data + '</div>';
11384
+
11385
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
11386
+
{
11387
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
11388
+
}
11389
+
var saving_index = '';
11390
+
var main_index = '';
11391
+
if(persistent == 'history')
11392
+
{
11393
+
saving_index = jQuery('#chat-log-identifier' + instance).val();
11394
+
main_index = jQuery('#chat-main-identifier' + instance).val();
11395
+
}
11396
+
appendx += '</div>';
11397
+
jQuery.ajax({
11398
+
type: 'POST',
11399
+
url: aiomatic_chat_ajax_object.ajax_url,
11400
+
data: {
11401
+
action: 'aiomatic_user_meta_save',
11402
+
nonce: aiomatic_chat_ajax_object.persistentnonce,
11403
+
persistent: persistent,
11404
+
thread_id: threadid,
11405
+
x_input_text: save_persistent + appendx,
11406
+
user_id: user_id,
11407
+
saving_index: saving_index,
11408
+
main_index: main_index
11409
+
},
11410
+
success: function(result)
11411
+
{
11412
+
if(result.name && result.msg)
11413
+
{
11414
+
var logsdrop = jQuery('#chat-logs-dropdown' + instance);
11415
+
if(logsdrop)
11416
+
{
11417
+
var newChatLogItem = jQuery('<div class="chat-log-item" id="chat-log-item' + saving_index + '" data-id="' + saving_index + '" onclick="aiomatic_trigger_chat_logs(\'' + saving_index + '\', \'' + instance + '\')">' + result.name + '<span onclick="aiomatic_remove_chat_logs(event, \'' + saving_index + '\', \'' + instance + '\');" class="aiomatic-remove-item">X</span></div>');
11418
+
var chatLogNew = logsdrop.find('.chat-log-new');
11419
+
if (chatLogNew.length)
11420
+
{
11421
+
var nextSibling = chatLogNew.next();
11422
+
if (nextSibling.length && nextSibling.hasClass('date-group-label'))
11423
+
{
11424
+
newChatLogItem.insertAfter(nextSibling);
11425
+
}
11426
+
else
11427
+
{
11428
+
newChatLogItem.insertAfter(chatLogNew);
11429
+
}
11430
+
}
11431
+
else
11432
+
{
11433
+
logsdrop.append(newChatLogItem);
11434
+
}
11435
+
}
11436
+
}
11437
+
},
11438
+
error: function(error) {
11439
+
console.log('Error while saving persistent user log: ' + error.responseText);
11440
+
},
11441
+
});
11442
+
}
11443
+
var speech_response_data = response.data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
11444
+
speech_response_data = aiomatic_stripHtmlTags(speech_response_data);
11445
+
if(instant_response == 'true' || instant_response == 'on')
11446
+
{
11447
+
var has_speech = false;
11448
+
if(aiomatic_chat_ajax_object.receive_message_sound != '')
11449
+
{
11450
+
var snd = new Audio(aiomatic_chat_ajax_object.receive_message_sound);
11451
+
snd.play();
11452
+
}
11453
+
if(!jQuery('.aiomatic-gg-unmute').length)
11454
+
{
11455
+
if(aiomatic_chat_ajax_object.text_speech == 'elevenlabs')
11456
+
{
11457
+
has_speech = true;
11458
+
let speechData = new FormData();
11459
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
11460
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
11461
+
speechData.append('x_input_text', speech_response_data);
11462
+
speechData.append('action', 'aiomatic_get_elevenlabs_voice_chat');
11463
+
var speechRequest = new XMLHttpRequest();
11464
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
11465
+
speechRequest.responseType = "arraybuffer";
11466
+
speechRequest.ontimeout = () => {
11467
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
11468
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11469
+
aiomaticRmLoading(chatbut, instance);
11470
+
aiomatic_generator_working = false;
11471
+
};
11472
+
speechRequest.onerror = function ()
11473
+
{
11474
+
console.error("Network Error");
11475
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11476
+
aiomaticRmLoading(chatbut, instance);
11477
+
aiomatic_generator_working = false;
11478
+
};
11479
+
speechRequest.onabort = function ()
11480
+
{
11481
+
console.error("The request was aborted.");
11482
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11483
+
aiomaticRmLoading(chatbut, instance);
11484
+
aiomatic_generator_working = false;
11485
+
};
11486
+
speechRequest.onload = function () {
11487
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
11488
+
var fr = new FileReader();
11489
+
fr.onload = function () {
11490
+
var fileText = this.result;
11491
+
try {
11492
+
var errorMessage = JSON.parse(fileText);
11493
+
console.log('ElevenLabs API failed: ' + errorMessage.msg);
11494
+
var appendx = '<div class="ai-wrapper">';
11495
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
11496
+
{
11497
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
11498
+
}
11499
+
appendx += '<div class="ai-bubble ai-other">' + response.data + '</div>';
11500
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
11501
+
{
11502
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
11503
+
}
11504
+
appendx += '</div>';
11505
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
11506
+
appendx = processKatexMarkdown(appendx);
11507
+
}
11508
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
11509
+
appendx = aiomatic_parseMarkdown(appendx);
11510
+
}
11511
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendx);
11512
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
11513
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
11514
+
renderMathInElement(katexContainer, {
11515
+
delimiters: [
11516
+
11517
+
{ left: '\\(', right: '\\)', display: false },
11518
+
{ left: '\\[', right: '\\]', display: true }
11519
+
],
11520
+
throwOnError: false
11521
+
});
11522
+
}
11523
+
// Clear the response container
11524
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11525
+
// Enable the submit button
11526
+
aiomaticRmLoading(chatbut, instance);
11527
+
} catch (errorBlob) {
11528
+
var blobUrl = URL.createObjectURL(blob);
11529
+
var audioElement = document.createElement('audio');
11530
+
audioElement.src = blobUrl;
11531
+
audioElement.controls = true;
11532
+
audioElement.style.marginTop = "2px";
11533
+
audioElement.style.width = "100%";
11534
+
audioElement.id = 'audio-element-' + instance;
11535
+
audioElement.addEventListener("error", function(event) {
11536
+
console.error("Error loading or playing the audio: ", event);
11537
+
});
11538
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
11539
+
appendx = processKatexMarkdown(appendx);
11540
+
}
11541
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
11542
+
appendx = aiomatic_parseMarkdown(appendx);
11543
+
}
11544
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
11545
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
11546
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
11547
+
renderMathInElement(katexContainer, {
11548
+
delimiters: [
11549
+
11550
+
{ left: '\\(', right: '\\)', display: false },
11551
+
{ left: '\\[', right: '\\]', display: true }
11552
+
],
11553
+
throwOnError: false
11554
+
});
11555
+
}
11556
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
11557
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
11558
+
{
11559
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
11560
+
var waveform = WaveSurfer.create({
11561
+
container: '#waveform-container' + instance,
11562
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
11563
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
11564
+
backend: 'MediaElement',
11565
+
height: 60,
11566
+
barWidth: 2,
11567
+
responsive: true, mediaControls: false, interact: false
11568
+
});
11569
+
waveform.setMuted(true);
11570
+
waveform.load(blobUrl);
11571
+
waveform.on('ready', function () {
11572
+
waveform.play();
11573
+
});
11574
+
audioElement.addEventListener('play', function () {
11575
+
waveform.play();
11576
+
});
11577
+
audioElement.addEventListener('pause', function () {
11578
+
waveform.pause();
11579
+
});
11580
+
}
11581
+
else
11582
+
{
11583
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11584
+
}
11585
+
audioElement.play();
11586
+
aiomaticRmLoading(chatbut, instance);
11587
+
aiomatic_generator_working = false;
11588
+
}
11589
+
}
11590
+
fr.readAsText(blob);
11591
+
}
11592
+
speechRequest.send(speechData);
11593
+
}
11594
+
else
11595
+
{
11596
+
if(aiomatic_chat_ajax_object.text_speech == 'openai')
11597
+
{
11598
+
has_speech = true;
11599
+
let speechData = new FormData();
11600
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
11601
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
11602
+
speechData.append('x_input_text', speech_response_data);
11603
+
speechData.append('action', 'aiomatic_get_openai_voice_chat');
11604
+
var speechRequest = new XMLHttpRequest();
11605
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
11606
+
speechRequest.responseType = "arraybuffer";
11607
+
speechRequest.ontimeout = () => {
11608
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
11609
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11610
+
aiomaticRmLoading(chatbut, instance);
11611
+
aiomatic_generator_working = false;
11612
+
};
11613
+
speechRequest.onerror = function ()
11614
+
{
11615
+
console.error("Network Error");
11616
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11617
+
aiomaticRmLoading(chatbut, instance);
11618
+
aiomatic_generator_working = false;
11619
+
};
11620
+
speechRequest.onabort = function ()
11621
+
{
11622
+
console.error("The request was aborted.");
11623
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11624
+
aiomaticRmLoading(chatbut, instance);
11625
+
aiomatic_generator_working = false;
11626
+
};
11627
+
speechRequest.onload = function () {
11628
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
11629
+
var fr = new FileReader();
11630
+
fr.onload = function () {
11631
+
var fileText = this.result;
11632
+
try {
11633
+
var errorMessage = JSON.parse(fileText);
11634
+
console.log('OpenAI TTS API failed: ' + errorMessage.msg);
11635
+
var appendx = '<div class="ai-wrapper">';
11636
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
11637
+
{
11638
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
11639
+
}
11640
+
appendx += '<div class="ai-bubble ai-other">' + response.data + '</div>';
11641
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
11642
+
{
11643
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
11644
+
}
11645
+
appendx += '</div>';
11646
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
11647
+
appendx = processKatexMarkdown(appendx);
11648
+
}
11649
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
11650
+
appendx = aiomatic_parseMarkdown(appendx);
11651
+
}
11652
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendx);
11653
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
11654
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
11655
+
renderMathInElement(katexContainer, {
11656
+
delimiters: [
11657
+
11658
+
{ left: '\\(', right: '\\)', display: false },
11659
+
{ left: '\\[', right: '\\]', display: true }
11660
+
],
11661
+
throwOnError: false
11662
+
});
11663
+
}
11664
+
// Clear the response container
11665
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11666
+
// Enable the submit button
11667
+
aiomaticRmLoading(chatbut, instance);
11668
+
} catch (errorBlob) {
11669
+
var blobUrl = URL.createObjectURL(blob);
11670
+
var audioElement = document.createElement('audio');
11671
+
audioElement.src = blobUrl;
11672
+
audioElement.controls = true;
11673
+
audioElement.style.marginTop = "2px";
11674
+
audioElement.style.width = "100%";
11675
+
audioElement.id = 'audio-element-' + instance;
11676
+
audioElement.addEventListener("error", function(event) {
11677
+
console.error("Error loading or playing the audio: ", event);
11678
+
});
11679
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
11680
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
11681
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
11682
+
{
11683
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
11684
+
var waveform = WaveSurfer.create({
11685
+
container: '#waveform-container' + instance,
11686
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
11687
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
11688
+
backend: 'MediaElement',
11689
+
height: 60,
11690
+
barWidth: 2,
11691
+
responsive: true, mediaControls: false, interact: false
11692
+
});
11693
+
waveform.setMuted(true);
11694
+
waveform.load(blobUrl);
11695
+
waveform.on('ready', function () {
11696
+
waveform.play();
11697
+
});
11698
+
audioElement.addEventListener('play', function () {
11699
+
11700
+
waveform.play();
11701
+
});
11702
+
audioElement.addEventListener('pause', function () {
11703
+
waveform.pause();
11704
+
});
11705
+
}
11706
+
else
11707
+
{
11708
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11709
+
}
11710
+
audioElement.play();
11711
+
aiomaticRmLoading(chatbut, instance);
11712
+
aiomatic_generator_working = false;
11713
+
}
11714
+
}
11715
+
fr.readAsText(blob);
11716
+
}
11717
+
speechRequest.send(speechData);
11718
+
}
11719
+
else
11720
+
{
11721
+
if(aiomatic_chat_ajax_object.text_speech == 'google')
11722
+
{
11723
+
has_speech = true;
11724
+
let speechData = new FormData();
11725
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
11726
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
11727
+
speechData.append('x_input_text', speech_response_data);
11728
+
speechData.append('action', 'aiomatic_get_google_voice_chat');
11729
+
var speechRequest = new XMLHttpRequest();
11730
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
11731
+
speechRequest.ontimeout = () => {
11732
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
11733
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11734
+
aiomaticRmLoading(chatbut, instance);
11735
+
aiomatic_generator_working = false;
11736
+
};
11737
+
speechRequest.onerror = function ()
11738
+
{
11739
+
console.error("Network Error");
11740
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11741
+
aiomaticRmLoading(chatbut, instance);
11742
+
aiomatic_generator_working = false;
11743
+
};
11744
+
speechRequest.onabort = function ()
11745
+
{
11746
+
console.error("The request was aborted.");
11747
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11748
+
aiomaticRmLoading(chatbut, instance);
11749
+
aiomatic_generator_working = false;
11750
+
};
11751
+
speechRequest.onload = function () {
11752
+
var result = speechRequest.responseText;
11753
+
try {
11754
+
var jsonresult = JSON.parse(result);
11755
+
if(jsonresult.status === 'success'){
11756
+
var byteCharacters = atob(jsonresult.audio);
11757
+
const byteNumbers = new Array(byteCharacters.length);
11758
+
for (let i = 0; i < byteCharacters.length; i++) {
11759
+
byteNumbers[i] = byteCharacters.charCodeAt(i);
11760
+
}
11761
+
const byteArray = new Uint8Array(byteNumbers);
11762
+
const blob = new Blob([byteArray], {type: 'audio/mp3'});
11763
+
var blobUrl = URL.createObjectURL(blob);
11764
+
var audioElement = document.createElement('audio');
11765
+
audioElement.src = blobUrl;
11766
+
audioElement.controls = true;
11767
+
audioElement.style.marginTop = "2px";
11768
+
audioElement.style.width = "100%";
11769
+
audioElement.id = 'audio-element-' + instance;
11770
+
audioElement.addEventListener("error", function(event) {
11771
+
console.error("Error loading or playing the audio: ", event);
11772
+
});
11773
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + '<div class="ai-speech"></div>');
11774
+
jQuery('#aiomatic_chat_history' + instance + ' .ai-speech:last').append(audioElement);
11775
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
11776
+
{
11777
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
11778
+
var waveform = WaveSurfer.create({
11779
+
container: '#waveform-container' + instance,
11780
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
11781
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
11782
+
backend: 'MediaElement',
11783
+
height: 60,
11784
+
barWidth: 2,
11785
+
responsive: true, mediaControls: false, interact: false
11786
+
});
11787
+
waveform.setMuted(true);
11788
+
waveform.load(blobUrl);
11789
+
waveform.on('ready', function () {
11790
+
waveform.play();
11791
+
});
11792
+
audioElement.addEventListener('play', function () {
11793
+
waveform.play();
11794
+
});
11795
+
audioElement.addEventListener('pause', function () {
11796
+
waveform.pause();
11797
+
});
11798
+
}
11799
+
else
11800
+
{
11801
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11802
+
}
11803
+
audioElement.play();
11804
+
aiomaticRmLoading(chatbut, instance);
11805
+
aiomatic_generator_working = false;
11806
+
}
11807
+
else{
11808
+
var errorMessageDetail = 'Google: ' + jsonresult.msg;
11809
+
var appendx = '<div class="ai-wrapper">';
11810
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
11811
+
{
11812
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
11813
+
}
11814
+
appendx += '<div class="ai-bubble ai-other">' + response.data + '</div>';
11815
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
11816
+
{
11817
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
11818
+
}
11819
+
appendx += '</div>';
11820
+
console.log('Google Text-to-Speech error: ' + errorMessageDetail);
11821
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
11822
+
appendx = processKatexMarkdown(appendx);
11823
+
}
11824
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
11825
+
appendx = aiomatic_parseMarkdown(appendx);
11826
+
}
11827
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendx);
11828
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
11829
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
11830
+
renderMathInElement(katexContainer, {
11831
+
delimiters: [
11832
+
11833
+
{ left: '\\(', right: '\\)', display: false },
11834
+
{ left: '\\[', right: '\\]', display: true }
11835
+
],
11836
+
throwOnError: false
11837
+
});
11838
+
}
11839
+
// Clear the response container
11840
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11841
+
// Enable the submit button
11842
+
aiomaticRmLoading(chatbut, instance);
11843
+
}
11844
+
}
11845
+
catch (errorSpeech){
11846
+
console.log('Exception in Google Text-to-Speech API: ' + errorSpeech);
11847
+
var appendx = '<div class="ai-wrapper">';
11848
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
11849
+
{
11850
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
11851
+
}
11852
+
appendx += '<div class="ai-bubble ai-other">' + response.data + '</div>';
11853
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
11854
+
{
11855
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
11856
+
}
11857
+
appendx += '</div>';
11858
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
11859
+
appendx = processKatexMarkdown(appendx);
11860
+
}
11861
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
11862
+
appendx = aiomatic_parseMarkdown(appendx);
11863
+
}
11864
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendx);
11865
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
11866
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
11867
+
renderMathInElement(katexContainer, {
11868
+
delimiters: [
11869
+
11870
+
{ left: '\\(', right: '\\)', display: false },
11871
+
{ left: '\\[', right: '\\]', display: true }
11872
+
],
11873
+
throwOnError: false
11874
+
});
11875
+
}
11876
+
// Clear the response container
11877
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11878
+
// Enable the submit button
11879
+
aiomaticRmLoading(chatbut, instance);
11880
+
}
11881
+
}
11882
+
speechRequest.send(speechData);
11883
+
}
11884
+
else
11885
+
{
11886
+
if(aiomatic_chat_ajax_object.text_speech == 'did')
11887
+
{
11888
+
has_speech = true;
11889
+
let speechData = new FormData();
11890
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
11891
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
11892
+
speechData.append('x_input_text', speech_response_data);
11893
+
speechData.append('action', 'aiomatic_get_d_id_video_chat');
11894
+
var speechRequest = new XMLHttpRequest();
11895
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
11896
+
speechRequest.ontimeout = () => {
11897
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
11898
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11899
+
aiomaticRmLoading(chatbut, instance);
11900
+
aiomatic_generator_working = false;
11901
+
};
11902
+
speechRequest.onerror = function ()
11903
+
{
11904
+
console.error("Network Error");
11905
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11906
+
aiomaticRmLoading(chatbut, instance);
11907
+
aiomatic_generator_working = false;
11908
+
};
11909
+
speechRequest.onabort = function ()
11910
+
{
11911
+
console.error("The request was aborted.");
11912
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11913
+
aiomaticRmLoading(chatbut, instance);
11914
+
aiomatic_generator_working = false;
11915
+
};
11916
+
speechRequest.onload = function () {
11917
+
var result = speechRequest.responseText;
11918
+
try
11919
+
{
11920
+
var jsonresult = JSON.parse(result);
11921
+
if(jsonresult.status === 'success')
11922
+
{
11923
+
var videoURL = '<video class="ai_video" autoplay="autoplay" controls="controls"><source src="' + jsonresult.video + '" type="video/mp4"></video>';
11924
+
var appendx = '<div class="ai-wrapper">';
11925
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
11926
+
{
11927
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
11928
+
}
11929
+
appendx += '<div class="ai-bubble ai-other">' + response.data + '</div>';
11930
+
appendx += '<div class="ai-video">' + videoURL + '</div>';
11931
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
11932
+
{
11933
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
11934
+
}
11935
+
appendx += '</div>';
11936
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
11937
+
appendx = processKatexMarkdown(appendx);
11938
+
}
11939
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
11940
+
appendx = aiomatic_parseMarkdown(appendx);
11941
+
}
11942
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendx);
11943
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
11944
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
11945
+
renderMathInElement(katexContainer, {
11946
+
delimiters: [
11947
+
11948
+
{ left: '\\(', right: '\\)', display: false },
11949
+
{ left: '\\[', right: '\\]', display: true }
11950
+
],
11951
+
throwOnError: false
11952
+
});
11953
+
}
11954
+
// Clear the response container
11955
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11956
+
// Enable the submit button
11957
+
aiomaticRmLoading(chatbut, instance);
11958
+
}
11959
+
else
11960
+
{
11961
+
var errorMessageDetail = 'D-ID: ' + jsonresult.msg;
11962
+
console.log('D-ID Text-to-video error: ' + errorMessageDetail);
11963
+
var appendx = '<div class="ai-wrapper">';
11964
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
11965
+
{
11966
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
11967
+
}
11968
+
appendx += '<div class="ai-bubble ai-other">' + response.data + '</div>';
11969
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
11970
+
{
11971
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
11972
+
}
11973
+
appendx += '</div>';
11974
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
11975
+
appendx = processKatexMarkdown(appendx);
11976
+
}
11977
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
11978
+
appendx = aiomatic_parseMarkdown(appendx);
11979
+
}
11980
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendx);
11981
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
11982
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
11983
+
renderMathInElement(katexContainer, {
11984
+
delimiters: [
11985
+
11986
+
{ left: '\\(', right: '\\)', display: false },
11987
+
{ left: '\\[', right: '\\]', display: true }
11988
+
],
11989
+
throwOnError: false
11990
+
});
11991
+
}
11992
+
// Clear the response container
11993
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
11994
+
// Enable the submit button
11995
+
aiomaticRmLoading(chatbut, instance);
11996
+
}
11997
+
}
11998
+
catch (errorSpeech){
11999
+
console.log('Exception in D-ID Text-to-video API: ' + errorSpeech);
12000
+
var appendx = '<div class="ai-wrapper">';
12001
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12002
+
{
12003
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12004
+
}
12005
+
appendx += '<div class="ai-bubble ai-other">' + response.data + '</div>';
12006
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12007
+
{
12008
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12009
+
}
12010
+
appendx += '</div>';
12011
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
12012
+
appendx = processKatexMarkdown(appendx);
12013
+
}
12014
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
12015
+
appendx = aiomatic_parseMarkdown(appendx);
12016
+
}
12017
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendx);
12018
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
12019
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
12020
+
renderMathInElement(katexContainer, {
12021
+
delimiters: [
12022
+
12023
+
{ left: '\\(', right: '\\)', display: false },
12024
+
{ left: '\\[', right: '\\]', display: true }
12025
+
],
12026
+
throwOnError: false
12027
+
});
12028
+
}
12029
+
// Clear the response container
12030
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
12031
+
// Enable the submit button
12032
+
aiomaticRmLoading(chatbut, instance);
12033
+
}
12034
+
}
12035
+
speechRequest.send(speechData);
12036
+
}
12037
+
else
12038
+
{
12039
+
if(aiomatic_chat_ajax_object.text_speech == 'didstream')
12040
+
{
12041
+
if(avatarImageUrl != '' && did_app_id != '')
12042
+
{
12043
+
if(streamingEpicFail === false)
12044
+
{
12045
+
has_speech = true;
12046
+
myStreamObject.talkToDidStream(speech_response_data);
12047
+
var appendx = '<div class="ai-wrapper">';
12048
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12049
+
{
12050
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12051
+
}
12052
+
appendx += '<div class="ai-bubble ai-other">' + response.data + '</div>';
12053
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12054
+
{
12055
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12056
+
}
12057
+
appendx += '</div>';
12058
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
12059
+
appendx = processKatexMarkdown(appendx);
12060
+
}
12061
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
12062
+
appendx = aiomatic_parseMarkdown(appendx);
12063
+
}
12064
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendx);
12065
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
12066
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
12067
+
renderMathInElement(katexContainer, {
12068
+
delimiters: [
12069
+
12070
+
{ left: '\\(', right: '\\)', display: false },
12071
+
{ left: '\\[', right: '\\]', display: true }
12072
+
],
12073
+
throwOnError: false
12074
+
});
12075
+
}
12076
+
// Clear the response container
12077
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
12078
+
}
12079
+
else
12080
+
{
12081
+
var appendx = '<div class="ai-wrapper">';
12082
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12083
+
{
12084
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12085
+
}
12086
+
appendx += '<div class="ai-bubble ai-other">' + response.data + '</div>';
12087
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12088
+
{
12089
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12090
+
}
12091
+
appendx += '</div>';
12092
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
12093
+
appendx = processKatexMarkdown(appendx);
12094
+
}
12095
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
12096
+
appendx = aiomatic_parseMarkdown(appendx);
12097
+
}
12098
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendx);
12099
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
12100
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
12101
+
renderMathInElement(katexContainer, {
12102
+
delimiters: [
12103
+
12104
+
{ left: '\\(', right: '\\)', display: false },
12105
+
{ left: '\\[', right: '\\]', display: true }
12106
+
],
12107
+
throwOnError: false
12108
+
});
12109
+
}
12110
+
// Clear the response container
12111
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
12112
+
}
12113
+
}
12114
+
else
12115
+
{
12116
+
var appendx = '<div class="ai-wrapper">';
12117
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12118
+
{
12119
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12120
+
}
12121
+
appendx += '<div class="ai-bubble ai-other">' + response.data + '</div>';
12122
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12123
+
{
12124
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12125
+
}
12126
+
appendx += '</div>';
12127
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
12128
+
appendx = processKatexMarkdown(appendx);
12129
+
}
12130
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
12131
+
appendx = aiomatic_parseMarkdown(appendx);
12132
+
}
12133
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendx);
12134
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
12135
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
12136
+
renderMathInElement(katexContainer, {
12137
+
delimiters: [
12138
+
12139
+
{ left: '\\(', right: '\\)', display: false },
12140
+
{ left: '\\[', right: '\\]', display: true }
12141
+
],
12142
+
throwOnError: false
12143
+
});
12144
+
}
12145
+
// Clear the response container
12146
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
12147
+
}
12148
+
}
12149
+
else
12150
+
{
12151
+
if(aiomatic_chat_ajax_object.text_speech == 'azure')
12152
+
{
12153
+
if(azure_speech_id != '')
12154
+
{
12155
+
if(streamingEpicFail === false)
12156
+
{
12157
+
has_speech = true;
12158
+
var ttsvoice = aiomatic_chat_ajax_object.azure_voice;
12159
+
var personalVoiceSpeakerProfileID = aiomatic_chat_ajax_object.azure_voice_profile;
12160
+
aiomaticRmLoading(chatbut, instance);
12161
+
azureSpeakText(speech_response_data, ttsvoice, personalVoiceSpeakerProfileID);
12162
+
var appendx = '<div class="ai-wrapper">';
12163
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12164
+
{
12165
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12166
+
}
12167
+
appendx += '<div class="ai-bubble ai-other">' + response.data + '</div>';
12168
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12169
+
{
12170
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12171
+
}
12172
+
appendx += '</div>';
12173
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
12174
+
appendx = processKatexMarkdown(appendx);
12175
+
}
12176
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
12177
+
appendx = aiomatic_parseMarkdown(appendx);
12178
+
}
12179
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendx);
12180
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
12181
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
12182
+
renderMathInElement(katexContainer, {
12183
+
delimiters: [
12184
+
12185
+
{ left: '\\(', right: '\\)', display: false },
12186
+
{ left: '\\[', right: '\\]', display: true }
12187
+
],
12188
+
throwOnError: false
12189
+
});
12190
+
}
12191
+
// Clear the response container
12192
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
12193
+
}
12194
+
else
12195
+
{
12196
+
var appendx = '<div class="ai-wrapper">';
12197
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12198
+
{
12199
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12200
+
}
12201
+
appendx += '<div class="ai-bubble ai-other">' + response.data + '</div>';
12202
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12203
+
{
12204
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12205
+
}
12206
+
appendx += '</div>';
12207
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
12208
+
appendx = processKatexMarkdown(appendx);
12209
+
}
12210
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
12211
+
appendx = aiomatic_parseMarkdown(appendx);
12212
+
}
12213
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendx);
12214
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
12215
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
12216
+
renderMathInElement(katexContainer, {
12217
+
delimiters: [
12218
+
12219
+
{ left: '\\(', right: '\\)', display: false },
12220
+
{ left: '\\[', right: '\\]', display: true }
12221
+
],
12222
+
throwOnError: false
12223
+
});
12224
+
}
12225
+
// Clear the response container
12226
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
12227
+
}
12228
+
}
12229
+
else
12230
+
{
12231
+
var appendx = '<div class="ai-wrapper">';
12232
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12233
+
{
12234
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12235
+
}
12236
+
appendx += '<div class="ai-bubble ai-other">' + response.data + '</div>';
12237
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12238
+
{
12239
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12240
+
}
12241
+
appendx += '</div>';
12242
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
12243
+
appendx = processKatexMarkdown(appendx);
12244
+
}
12245
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
12246
+
appendx = aiomatic_parseMarkdown(appendx);
12247
+
}
12248
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendx);
12249
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
12250
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
12251
+
renderMathInElement(katexContainer, {
12252
+
delimiters: [
12253
+
12254
+
{ left: '\\(', right: '\\)', display: false },
12255
+
{ left: '\\[', right: '\\]', display: true }
12256
+
],
12257
+
throwOnError: false
12258
+
});
12259
+
}
12260
+
// Clear the response container
12261
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
12262
+
}
12263
+
}
12264
+
else
12265
+
{
12266
+
if(aiomatic_chat_ajax_object.text_speech == 'free')
12267
+
{
12268
+
var T2S;
12269
+
if("speechSynthesis" in window || speechSynthesis)
12270
+
{
12271
+
var response_data = response.data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
12272
+
response_data = aiomatic_stripHtmlTags(response_data);
12273
+
if(response_data != '')
12274
+
{
12275
+
T2S = window.speechSynthesis || speechSynthesis;
12276
+
var utter = new SpeechSynthesisUtterance(response_data);
12277
+
var voiceSetting = aiomatic_chat_ajax_object.free_voice.split(";");
12278
+
var desiredVoiceName = voiceSetting[0].trim();
12279
+
var desiredLang = voiceSetting[1].trim();
12280
+
var voices = T2S.getVoices();
12281
+
var selectedVoice = voices.find(function(voice) {
12282
+
return voice.name === desiredVoiceName && voice.lang === desiredLang;
12283
+
});
12284
+
if (selectedVoice) {
12285
+
utter.voice = selectedVoice;
12286
+
utter.lang = selectedVoice.lang;
12287
+
}
12288
+
else
12289
+
{
12290
+
utter.lang = desiredLang;
12291
+
}
12292
+
T2S.speak(utter);
12293
+
}
12294
+
}
12295
+
}
12296
+
var appendx = '<div class="ai-wrapper">';
12297
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12298
+
{
12299
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12300
+
}
12301
+
appendx += '<div class="ai-bubble ai-other">' + response.data + '</div>';
12302
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12303
+
{
12304
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12305
+
}
12306
+
appendx += '</div>';
12307
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
12308
+
appendx = processKatexMarkdown(appendx);
12309
+
}
12310
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
12311
+
appendx = aiomatic_parseMarkdown(appendx);
12312
+
}
12313
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendx);
12314
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
12315
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
12316
+
renderMathInElement(katexContainer, {
12317
+
delimiters: [
12318
+
12319
+
{ left: '\\(', right: '\\)', display: false },
12320
+
{ left: '\\[', right: '\\]', display: true }
12321
+
],
12322
+
throwOnError: false
12323
+
});
12324
+
}
12325
+
// Clear the response container
12326
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
12327
+
// Enable the submit button
12328
+
aiomaticRmLoading(chatbut, instance);
12329
+
}
12330
+
}
12331
+
}
12332
+
}
12333
+
}
12334
+
}
12335
+
}
12336
+
else
12337
+
{
12338
+
var appendx = '<div class="ai-wrapper">';
12339
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12340
+
{
12341
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12342
+
}
12343
+
appendx += '<div class="ai-bubble ai-other">' + response.data + '</div>';
12344
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12345
+
{
12346
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12347
+
}
12348
+
appendx += '</div>';
12349
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
12350
+
appendx = processKatexMarkdown(appendx);
12351
+
}
12352
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
12353
+
appendx = aiomatic_parseMarkdown(appendx);
12354
+
}
12355
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendx);
12356
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
12357
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
12358
+
renderMathInElement(katexContainer, {
12359
+
delimiters: [
12360
+
12361
+
{ left: '\\(', right: '\\)', display: false },
12362
+
{ left: '\\[', right: '\\]', display: true }
12363
+
],
12364
+
throwOnError: false
12365
+
});
12366
+
}
12367
+
// Clear the response container
12368
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
12369
+
// Enable the submit button
12370
+
aiomaticRmLoading(chatbut, instance);
12371
+
}
12372
+
}
12373
+
else
12374
+
{
12375
+
var speak_now = false;
12376
+
var has_speech = false;
12377
+
if(aiomatic_chat_ajax_object.receive_message_sound != '')
12378
+
{
12379
+
var snd = new Audio(aiomatic_chat_ajax_object.receive_message_sound);
12380
+
snd.play();
12381
+
}
12382
+
if(!jQuery('.aiomatic-gg-unmute').length)
12383
+
{
12384
+
if(aiomatic_chat_ajax_object.text_speech == 'elevenlabs')
12385
+
{
12386
+
has_speech = true;
12387
+
speak_now = true;
12388
+
let speechData = new FormData();
12389
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
12390
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
12391
+
speechData.append('x_input_text', speech_response_data);
12392
+
speechData.append('action', 'aiomatic_get_elevenlabs_voice_chat');
12393
+
var speechRequest = new XMLHttpRequest();
12394
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
12395
+
speechRequest.responseType = "arraybuffer";
12396
+
speechRequest.ontimeout = () => {
12397
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
12398
+
aiomatic_generator_working = false;
12399
+
typeWriter();
12400
+
};
12401
+
speechRequest.onerror = function ()
12402
+
{
12403
+
console.error("Network Error");
12404
+
aiomatic_generator_working = false;
12405
+
typeWriter();
12406
+
};
12407
+
speechRequest.onabort = function ()
12408
+
{
12409
+
console.error("The request was aborted.");
12410
+
aiomatic_generator_working = false;
12411
+
typeWriter();
12412
+
};
12413
+
speechRequest.onload = function () {
12414
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
12415
+
var fr = new FileReader();
12416
+
fr.onload = function () {
12417
+
var fileText = this.result;
12418
+
try {
12419
+
var errorMessage = JSON.parse(fileText);
12420
+
console.log('ElevenLabs API failed: ' + errorMessage.msg);
12421
+
typeWriter();
12422
+
} catch (errorBlob) {
12423
+
var blobUrl = URL.createObjectURL(blob);
12424
+
var audioElement = document.createElement('audio');
12425
+
audioElement.src = blobUrl;
12426
+
audioElement.controls = true;
12427
+
audioElement.style.marginTop = "2px";
12428
+
audioElement.style.width = "100%";
12429
+
audioElement.id = 'audio-element-' + instance;
12430
+
audioElement.addEventListener("error", function(event)
12431
+
{
12432
+
console.error("Error loading or playing the audio: ", event);
12433
+
});
12434
+
var aiomatic_speech = audioElement.outerHTML;
12435
+
response.data += '</div>' + '<div class="ai-speech">' + aiomatic_speech;
12436
+
typeWriter();
12437
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
12438
+
{
12439
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
12440
+
var waveform = WaveSurfer.create({
12441
+
container: '#waveform-container' + instance,
12442
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
12443
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
12444
+
backend: 'MediaElement',
12445
+
height: 60,
12446
+
barWidth: 2,
12447
+
responsive: true, mediaControls: false, interact: false
12448
+
});
12449
+
waveform.setMuted(true);
12450
+
waveform.load(blobUrl);
12451
+
waveform.on('ready', function () {
12452
+
waveform.play();
12453
+
});
12454
+
audioElement.addEventListener('play', function () {
12455
+
waveform.play();
12456
+
});
12457
+
audioElement.addEventListener('pause', function () {
12458
+
waveform.pause();
12459
+
});
12460
+
}
12461
+
else
12462
+
{
12463
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
12464
+
}
12465
+
audioElement.play();
12466
+
}
12467
+
}
12468
+
fr.readAsText(blob);
12469
+
}
12470
+
speechRequest.send(speechData);
12471
+
}
12472
+
else
12473
+
{
12474
+
if(aiomatic_chat_ajax_object.text_speech == 'openai')
12475
+
{
12476
+
speak_now = true;
12477
+
has_speech = true;
12478
+
let speechData = new FormData();
12479
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
12480
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
12481
+
speechData.append('x_input_text', speech_response_data);
12482
+
speechData.append('action', 'aiomatic_get_openai_voice_chat');
12483
+
var speechRequest = new XMLHttpRequest();
12484
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
12485
+
speechRequest.responseType = "arraybuffer";
12486
+
speechRequest.ontimeout = () => {
12487
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
12488
+
aiomatic_generator_working = false;
12489
+
typeWriter();
12490
+
};
12491
+
speechRequest.onerror = function ()
12492
+
{
12493
+
console.error("Network Error");
12494
+
aiomatic_generator_working = false;
12495
+
typeWriter();
12496
+
};
12497
+
speechRequest.onabort = function ()
12498
+
{
12499
+
console.error("The request was aborted.");
12500
+
aiomatic_generator_working = false;
12501
+
typeWriter();
12502
+
};
12503
+
speechRequest.onload = function () {
12504
+
var blob = new Blob([speechRequest.response], {type: "audio/mpeg"});
12505
+
var fr = new FileReader();
12506
+
fr.onload = function () {
12507
+
var fileText = this.result;
12508
+
try {
12509
+
var errorMessage = JSON.parse(fileText);
12510
+
console.log('OpenAI TTS API failed: ' + errorMessage.msg);
12511
+
typeWriter();
12512
+
} catch (errorBlob) {
12513
+
var blobUrl = URL.createObjectURL(blob);
12514
+
var audioElement = document.createElement('audio');
12515
+
audioElement.src = blobUrl;
12516
+
audioElement.controls = true;
12517
+
audioElement.style.marginTop = "2px";
12518
+
audioElement.style.width = "100%";
12519
+
audioElement.id = 'audio-element-' + instance;
12520
+
audioElement.addEventListener("error", function(event)
12521
+
{
12522
+
console.error("Error loading or playing the audio: ", event);
12523
+
});
12524
+
var aiomatic_speech = audioElement.outerHTML;
12525
+
response.data += '</div>' + '<div class="ai-speech">' + aiomatic_speech;
12526
+
typeWriter();
12527
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
12528
+
{
12529
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
12530
+
var waveform = WaveSurfer.create({
12531
+
container: '#waveform-container' + instance,
12532
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
12533
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
12534
+
backend: 'MediaElement',
12535
+
height: 60,
12536
+
barWidth: 2,
12537
+
responsive: true, mediaControls: false, interact: false
12538
+
});
12539
+
waveform.setMuted(true);
12540
+
waveform.load(blobUrl);
12541
+
waveform.on('ready', function () {
12542
+
waveform.play();
12543
+
});
12544
+
audioElement.addEventListener('play', function () {
12545
+
waveform.play();
12546
+
});
12547
+
audioElement.addEventListener('pause', function () {
12548
+
waveform.pause();
12549
+
});
12550
+
}
12551
+
else
12552
+
{
12553
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
12554
+
}
12555
+
audioElement.play();
12556
+
}
12557
+
}
12558
+
fr.readAsText(blob);
12559
+
}
12560
+
speechRequest.send(speechData);
12561
+
}
12562
+
else
12563
+
{
12564
+
if(aiomatic_chat_ajax_object.text_speech == 'google')
12565
+
{
12566
+
speak_now = true;
12567
+
has_speech = true;
12568
+
let speechData = new FormData();
12569
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
12570
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
12571
+
speechData.append('x_input_text', speech_response_data);
12572
+
speechData.append('action', 'aiomatic_get_google_voice_chat');
12573
+
var speechRequest = new XMLHttpRequest();
12574
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
12575
+
speechRequest.ontimeout = () => {
12576
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
12577
+
aiomatic_generator_working = false;
12578
+
typeWriter();
12579
+
};
12580
+
speechRequest.onerror = function ()
12581
+
{
12582
+
console.error("Network Error");
12583
+
aiomatic_generator_working = false;
12584
+
typeWriter();
12585
+
};
12586
+
speechRequest.onabort = function ()
12587
+
{
12588
+
console.error("The request was aborted.");
12589
+
aiomatic_generator_working = false;
12590
+
typeWriter();
12591
+
};
12592
+
speechRequest.onload = function () {
12593
+
var result = speechRequest.responseText;
12594
+
try {
12595
+
var jsonresult = JSON.parse(result);
12596
+
if(jsonresult.status === 'success'){
12597
+
var byteCharacters = atob(jsonresult.audio);
12598
+
const byteNumbers = new Array(byteCharacters.length);
12599
+
for (let i = 0; i < byteCharacters.length; i++) {
12600
+
byteNumbers[i] = byteCharacters.charCodeAt(i);
12601
+
}
12602
+
const byteArray = new Uint8Array(byteNumbers);
12603
+
const blob = new Blob([byteArray], {type: 'audio/mp3'});
12604
+
var blobUrl = URL.createObjectURL(blob);
12605
+
var audioElement = document.createElement('audio');
12606
+
audioElement.src = blobUrl;
12607
+
audioElement.controls = true;
12608
+
audioElement.style.marginTop = "2px";
12609
+
audioElement.style.width = "100%";
12610
+
audioElement.id = 'audio-element-' + instance;
12611
+
audioElement.addEventListener("error", function(event)
12612
+
{
12613
+
console.error("Error loading or playing the audio: ", event);
12614
+
});
12615
+
var aiomatic_speech = audioElement.outerHTML;
12616
+
response.data += '</div>' + '<div class="ai-speech">' + aiomatic_speech;
12617
+
typeWriter();
12618
+
if(aiomatic_chat_ajax_object.chat_waveform == 'on')
12619
+
{
12620
+
jQuery('#openai-chat-response' + instance).html('<div id="waveform-container' + instance + '" style="width: 100%; height: 60px;"></div></div>');
12621
+
var waveform = WaveSurfer.create({
12622
+
container: '#waveform-container' + instance,
12623
+
waveColor: aiomatic_chat_ajax_object.waveform_color,
12624
+
progressColor: aiomatic_chat_ajax_object.waveform_color,
12625
+
backend: 'MediaElement',
12626
+
height: 60,
12627
+
barWidth: 2,
12628
+
responsive: true, mediaControls: false, interact: false
12629
+
});
12630
+
waveform.setMuted(true);
12631
+
waveform.load(blobUrl);
12632
+
waveform.on('ready', function () {
12633
+
waveform.play();
12634
+
});
12635
+
audioElement.addEventListener('play', function () {
12636
+
waveform.play();
12637
+
});
12638
+
audioElement.addEventListener('pause', function () {
12639
+
waveform.pause();
12640
+
});
12641
+
}
12642
+
else
12643
+
{
12644
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
12645
+
}
12646
+
audioElement.play();
12647
+
}
12648
+
else{
12649
+
var errorMessageDetail = 'Google: ' + jsonresult.msg;
12650
+
console.log('Google Text-to-Speech error: ' + errorMessageDetail);
12651
+
typeWriter();
12652
+
}
12653
+
}
12654
+
catch (errorSpeech){
12655
+
console.log('Exception in Google Text-to-Speech API: ' + errorSpeech);
12656
+
typeWriter();
12657
+
}
12658
+
}
12659
+
speechRequest.send(speechData);
12660
+
}
12661
+
else
12662
+
{
12663
+
if(aiomatic_chat_ajax_object.text_speech == 'did')
12664
+
{
12665
+
speak_now = true;
12666
+
has_speech = true;
12667
+
let speechData = new FormData();
12668
+
speechData.append('nonce', aiomatic_chat_ajax_object.nonce);
12669
+
speechData.append('overwrite_voice', aiomatic_chat_ajax_object.overwrite_voice);
12670
+
speechData.append('x_input_text', speech_response_data);
12671
+
speechData.append('action', 'aiomatic_get_d_id_video_chat');
12672
+
var speechRequest = new XMLHttpRequest();
12673
+
speechRequest.open("POST", aiomatic_chat_ajax_object.ajax_url);
12674
+
speechRequest.ontimeout = () => {
12675
+
console.error(`The request for ` + aiomatic_chat_ajax_object.ajax_url + ` timed out.`);
12676
+
aiomatic_generator_working = false;
12677
+
typeWriter();
12678
+
};
12679
+
speechRequest.onerror = function ()
12680
+
{
12681
+
console.error("Network Error");
12682
+
aiomatic_generator_working = false;
12683
+
typeWriter();
12684
+
};
12685
+
speechRequest.onabort = function ()
12686
+
{
12687
+
console.error("The request was aborted.");
12688
+
aiomatic_generator_working = false;
12689
+
typeWriter();
12690
+
};
12691
+
speechRequest.onload = function () {
12692
+
var result = speechRequest.responseText;
12693
+
try
12694
+
{
12695
+
var jsonresult = JSON.parse(result);
12696
+
if(jsonresult.status === 'success')
12697
+
{
12698
+
var videoURL = '<video class="ai_video" autoplay="autoplay" controls="controls"><source src="' + jsonresult.video + '" type="video/mp4"></video>';
12699
+
response.data += '</div>' + '<div class="ai-video">' + videoURL;
12700
+
typeWriter();
12701
+
}
12702
+
else
12703
+
{
12704
+
var errorMessageDetail = 'D-ID: ' + jsonresult.msg;
12705
+
console.log('D-ID Text-to-video error: ' + errorMessageDetail);
12706
+
typeWriter();
12707
+
}
12708
+
}
12709
+
catch (errorSpeech){
12710
+
console.log('Exception in D-ID Text-to-video API: ' + errorSpeech);
12711
+
typeWriter();
12712
+
}
12713
+
}
12714
+
speechRequest.send(speechData);
12715
+
}
12716
+
else
12717
+
{
12718
+
if(aiomatic_chat_ajax_object.text_speech == 'didstream')
12719
+
{
12720
+
if(avatarImageUrl != '' && did_app_id != '')
12721
+
{
12722
+
if(streamingEpicFail === false)
12723
+
{
12724
+
has_speech = true;
12725
+
myStreamObject.talkToDidStream(speech_response_data);
12726
+
}
12727
+
}
12728
+
}
12729
+
else
12730
+
{
12731
+
if(aiomatic_chat_ajax_object.text_speech == 'azure')
12732
+
{
12733
+
if(azure_speech_id != '')
12734
+
{
12735
+
if(streamingEpicFail === false)
12736
+
{
12737
+
has_speech = true;
12738
+
var ttsvoice = aiomatic_chat_ajax_object.azure_voice;
12739
+
var personalVoiceSpeakerProfileID = aiomatic_chat_ajax_object.azure_voice_profile;
12740
+
aiomaticRmLoading(chatbut, instance);
12741
+
azureSpeakText(speech_response_data, ttsvoice, personalVoiceSpeakerProfileID);
12742
+
}
12743
+
}
12744
+
}
12745
+
else
12746
+
{
12747
+
if(aiomatic_chat_ajax_object.text_speech == 'free')
12748
+
{
12749
+
var T2S;
12750
+
if("speechSynthesis" in window || speechSynthesis)
12751
+
{
12752
+
var response_data = response.data.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g, '');
12753
+
response_data = aiomatic_stripHtmlTags(response_data);
12754
+
if(response_data != '')
12755
+
{
12756
+
T2S = window.speechSynthesis || speechSynthesis;
12757
+
var utter = new SpeechSynthesisUtterance(response_data);
12758
+
var voiceSetting = aiomatic_chat_ajax_object.free_voice.split(";");
12759
+
var desiredVoiceName = voiceSetting[0].trim();
12760
+
var desiredLang = voiceSetting[1].trim();
12761
+
var voices = T2S.getVoices();
12762
+
var selectedVoice = voices.find(function(voice) {
12763
+
return voice.name === desiredVoiceName && voice.lang === desiredLang;
12764
+
});
12765
+
if (selectedVoice) {
12766
+
utter.voice = selectedVoice;
12767
+
utter.lang = selectedVoice.lang;
12768
+
}
12769
+
else
12770
+
{
12771
+
utter.lang = desiredLang;
12772
+
}
12773
+
T2S.speak(utter);
12774
+
}
12775
+
}
12776
+
}
12777
+
}
12778
+
}
12779
+
}
12780
+
}
12781
+
}
12782
+
}
12783
+
}
12784
+
var i = 0;
12785
+
function typeWriter() {
12786
+
if (i < response.data.length) {
12787
+
// Append the response to the input field
12788
+
var appendx = '<div class="ai-wrapper">';
12789
+
if(aiomatic_chat_ajax_object.bubble_alignment != 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12790
+
{
12791
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12792
+
}
12793
+
appendx += '<div class="ai-bubble ai-other">' + response.data.substring(0, i + 1) + '</div>';
12794
+
if(aiomatic_chat_ajax_object.bubble_alignment == 'right' && aiomatic_chat_ajax_object.avatar_url != '' && aiomatic_chat_ajax_object.show_ai_avatar == 'show')
12795
+
{
12796
+
appendx += '<div class="ai-avatar ai-other' + responded + '"></div>';
12797
+
}
12798
+
appendx += '</div>';
12799
+
if (aiomatic_chat_ajax_object.katex_parse == 'on') {
12800
+
appendx = processKatexMarkdown(appendx);
12801
+
}
12802
+
if (aiomatic_chat_ajax_object.markdown_parse == 'on') {
12803
+
appendx = aiomatic_parseMarkdown(appendx);
12804
+
}
12805
+
jQuery('#aiomatic_chat_history' + instance).html(x_input_text + appendx);
12806
+
if (aiomatic_chat_ajax_object.katex_parse == 'on' && typeof renderMathInElement === 'function') {
12807
+
var katexContainer = document.getElementById('aiomatic_chat_history' + instance);
12808
+
renderMathInElement(katexContainer, {
12809
+
delimiters: [
12810
+
12811
+
{ left: '\\(', right: '\\)', display: false },
12812
+
{ left: '\\[', right: '\\]', display: true }
12813
+
],
12814
+
throwOnError: false
12815
+
});
12816
+
}
12817
+
i++;
12818
+
setTimeout(typeWriter, aiomatic_chat_ajax_object.typewriter_delay);
12819
+
} else {
12820
+
// Clear the response container
12821
+
const input = jQuery('#aiomatic_chat_input' + instance);if (!input.prop('chatended')) {jQuery('#openai-chat-response' + instance).html(' ');}
12822
+
// Enable the submit button
12823
+
aiomaticRmLoading(chatbut, instance);
12824
+
i = 0;
12825
+
}
12826
+
}
12827
+
jQuery('#openai-chat-response' + instance).html('');
12828
+
if(speak_now === false)
12829
+
{
12830
+
typeWriter();
12831
+
}
12832
+
}
12833
+
}
12834
+
}
12835
+
else
12836
+
{
12837
+
if(typeof response.msg !== 'undefined')
12838
+
{
12839
+
console.log('Error: ' + JSON.stringify(response));
12840
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + response.msg + '</div>');
12841
+
aiomaticRmLoading(chatbut, instance);
12842
+
}
12843
+
else
12844
+
{
12845
+
console.log('Error: ' + response);
12846
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
12847
+
aiomaticRmLoading(chatbut, instance);
12848
+
}
12849
+
}
12850
+
if(has_speech === false)
12851
+
{
12852
+
aiomaticRmLoading(chatbut, instance);
12853
+
}
12854
+
},
12855
+
error: function(error)
12856
+
{
12857
+
console.log('Error: ' + error.responseText);
12858
+
// Clear the response container
12859
+
jQuery('#openai-chat-response' + instance).html('<div class="text-primary highlight-text" role="status">' + aiomatic_chat_ajax_object.processing_issue + '</div>');
12860
+
// Enable the submit button
12861
+
aiomaticRmLoading(chatbut, instance);
12862
+
},
12863
+
});
12864
+
}
12865
+
}
12866
+
}
12867
+
var recognition;
12868
+
var recognizing = false;
12869
+
if(aiomatic_chat_ajax_object.enable_copy == 'on')
12870
+
{
12871
+
jQuery(document).on('click', '.ai-bubble', function (event) {
12872
+
var finder = jQuery(event.target);
12873
+
if(finder !== null)
12874
+
{
12875
+
var jsf = finder.html();
12876
+
var nlregex = /<br\s*[\/]?>/gi;
12877
+
jsf = jsf.replace(nlregex, "\n");
12878
+
var multiNlRegex = /\n+\s*/g;
12879
+
jsf = jsf.replace(multiNlRegex, "\n");
12880
+
if(navigator.clipboard !== undefined)
12881
+
{
12882
+
navigator.clipboard.writeText(jsf);
12883
+
}
12884
+
}
12885
+
var popup = jQuery("<div class='popup'>" + aiomatic_chat_ajax_object.text_copied + "</div>");
12886
+
popup.appendTo("body");
12887
+
popup.css({
12888
+
"position": "absolute",
12889
+
"top": event.pageY + 10,
12890
+
"left": event.pageX + 10
12891
+
});
12892
+
jQuery(document).mousemove(function(event) {
12893
+
popup.css({
12894
+
"position": "absolute",
12895
+
"top": event.pageY + 10,
12896
+
"left": event.pageX + 10
12897
+
});
12898
+
});
12899
+
setTimeout(function() {
12900
+
popup.remove();
12901
+
}, 3000);
12902
+
});
12903
+
}
12904
+
if(aiomatic_chat_ajax_object.scroll_bot == 'on')
12905
+
{
12906
+
var targetNode = document.querySelector('#aiomatic_chat_history' + instance);
12907
+
var observer = new MutationObserver(function(mutationsList, observer) {
12908
+
var psconsole = jQuery('#aiomatic_chat_history' + instance);
12909
+
if(psconsole.length) {
12910
+
psconsole.scrollTop(psconsole[0].scrollHeight - psconsole.height());
12911
+
}
12912
+
});
12913
+
var config = { childList: true, subtree: true };
12914
+
if (targetNode) {
12915
+
observer.observe(targetNode, config);
12916
+
}
12917
+
}
12918
+
if(jQuery('#aiomatic_chat_templates' + instance).length)
12919
+
{
12920
+
jQuery('#aiomatic_chat_templates' + instance).on('change', function()
12921
+
{
12922
+
jQuery('#aiomatic_chat_input' + instance).val(jQuery( "#aiomatic_chat_templates" + instance ).val());
12923
+
});
12924
+
}
12925
+
// Check if the browser supports the Web Speech API
12926
+
if ('webkitSpeechRecognition' in window) {
12927
+
recognition = new webkitSpeechRecognition();
12928
+
recognition.onerror = function(event)
12929
+
{
12930
+
console.log('Failed to start speech recognition: ' + JSON.stringify(event));
12931
+
recognizing = false;
12932
+
if(aiomatic_chat_ajax_object.voice_color !== undefined && aiomatic_chat_ajax_object.voice_color != '' && aiomatic_chat_ajax_object.voice_color != null && aiomatic_chat_ajax_object.voice_color_activated !== undefined && aiomatic_chat_ajax_object.voice_color_activated != '' && aiomatic_chat_ajax_object.voice_color_activated != null)
12933
+
{
12934
+
document.querySelector( '#openai-chat-speech-button' + instance ).style.setProperty( 'background-color', aiomatic_chat_ajax_object.voice_color, 'important' );
12935
+
}
12936
+
}
12937
+
12938
+
recognition.onend = function()
12939
+
{
12940
+
recognizing = false;
12941
+
if(aiomatic_chat_ajax_object.voice_color !== undefined && aiomatic_chat_ajax_object.voice_color != '' && aiomatic_chat_ajax_object.voice_color != null && aiomatic_chat_ajax_object.voice_color_activated !== undefined && aiomatic_chat_ajax_object.voice_color_activated != '' && aiomatic_chat_ajax_object.voice_color_activated != null)
12942
+
{
12943
+
document.querySelector( '#openai-chat-speech-button' + instance ).style.setProperty( 'background-color', aiomatic_chat_ajax_object.voice_color, 'important' );
12944
+
}
12945
+
}
12946
+
recognition.continuous = true;
12947
+
recognition.interimResults = true;
12948
+
12949
+
// Start the speech recognition when the button is clicked
12950
+
jQuery('#openai-chat-speech-button' + instance).on('click', function()
12951
+
{
12952
+
if (recognizing)
12953
+
{
12954
+
try{
12955
+
recognition.stop();
12956
+
}
12957
+
catch(e)
12958
+
{
12959
+
console.log('Speech recognition stop error: ' + e);
12960
+
}
12961
+
recognizing = false;
12962
+
if(aiomatic_chat_ajax_object.voice_color !== undefined && aiomatic_chat_ajax_object.voice_color != '' && aiomatic_chat_ajax_object.voice_color != null && aiomatic_chat_ajax_object.voice_color_activated !== undefined && aiomatic_chat_ajax_object.voice_color_activated != '' && aiomatic_chat_ajax_object.voice_color_activated != null)
12963
+
{
12964
+
this.style.setProperty( 'background-color', aiomatic_chat_ajax_object.voice_color, 'important' );
12965
+
}
12966
+
}
12967
+
else
12968
+
{
12969
+
try{
12970
+
recognition.start();
12971
+
}
12972
+
catch(e)
12973
+
{
12974
+
console.log('Speech recognition start error: ' + e);
12975
+
}
12976
+
recognizing = true;
12977
+
if(aiomatic_chat_ajax_object.voice_color !== undefined && aiomatic_chat_ajax_object.voice_color != '' && aiomatic_chat_ajax_object.voice_color != null && aiomatic_chat_ajax_object.voice_color_activated !== undefined && aiomatic_chat_ajax_object.voice_color_activated != '' && aiomatic_chat_ajax_object.voice_color_activated != null)
12978
+
{
12979
+
this.style.setProperty( 'background-color', aiomatic_chat_ajax_object.voice_color_activated, 'important' );
12980
+
}
12981
+
}
12982
+
});
12983
+
12984
+
// Handle the speech recognition results
12985
+
recognition.onresult = function(event) {
12986
+
for (var i = event.resultIndex; i < event.results.length; ++i) {
12987
+
if (event.results[i].isFinal) {
12988
+
jQuery('#aiomatic_chat_input' + instance).val(jQuery('#aiomatic_chat_input' + instance).val() + " " + event.results[i][0].transcript);
12989
+
if(aiomatic_chat_ajax_object.auto_submit_voice == 'on')
12990
+
{
12991
+
jQuery('#aichatsubmitbut' + instance).click();
12992
+
}
12993
+
}
12994
+
}
12995
+
12996
+
};
12997
+
}
12998
+
else
12999
+
{
13000
+
console.log('Web speech API is not supported by your browser!');
13001
+
jQuery('#openai-chat-speech-button' + instance).on('click', function() {
13002
+
alert('Speech recognition is not supported by your browser. Please type your input manually.');
13003
+
});
13004
+
}
13005
+
}