PluginProbe
WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services / 6.6.0
WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services v6.6.0
8.7.8 8.7.7 8.7.6 8.7.5 8.7.4 8.7.3 8.7.2 8.7.1 8.7.0 8.6.9 8.6.8 8.6.7 8.6.6 8.6.5 8.6.4 8.6.2 8.6.1 8.6.0 8.5.9 8.5.8 8.5.7 8.5.6 8.5.5 8.5.4 8.5.3 All 534 releases
chatbot / includes / openai / qcld-bot-openai.php

qcld-bot-openai.php in WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services 6.6.0, at includes/openai/qcld-bot-openai.php

760 lines 35.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 if (!defined('ABSPATH')) exit; // Exit if accessed directly
3
4 if(!class_exists('qcld_wpopenai_addons')){
5
6
7 /**
8 * Main Class.
9 */
10 final class qcld_wpopenai_addons
11 {
12 private $id = 'Open AI';
13
14 /**
15 * WPBot Pro version.
16 *
17 * @var string
18 */
19 public $version = '1.0.6';
20
21 /**
22 * WPBot Pro helper.
23 *
24 * @var object
25 */
26 public $helper;
27
28 /**
29 * The single instance of the class.
30 *
31 * @var qcld_wb_Chatbot
32 * @since 1.0.0
33 */
34 protected static $_instance = null;
35
36 /**
37 * Main wpbot Instance.
38 *
39 * Ensures only one instance of wpbot is loaded or can be loaded.
40 *
41 * @return qcld_wb_Chatbot - Main instance.
42 * @since 1.0.0
43 * @static
44 */
45 public static function instance() {
46 if ( is_null( self::$_instance ) ) {
47 self::$_instance = new self();
48 }
49
50 return self::$_instance;
51 }
52
53 public $response_list;
54
55 /**
56 * Constructor
57 */
58 public function __construct()
59 {
60 $this->define_constants();
61 $this->includes();
62 add_action('wp_ajax_openai_settings_option', [$this, 'openai_settings_option_callback']);
63 add_action('wp_ajax_openai_response',[$this,'openai_response_callback']);
64 add_action('wp_ajax_nopriv_openai_response', [$this, 'openai_response_callback']);
65 add_action('wp_ajax_openai_troubleshooting',[$this,'openai_troubleshooting']);
66 if (is_admin() && !empty($_GET["page"]) && (($_GET["page"] == "openai-panel_dashboard") || ($_GET["page"] == "openai-panel_file") || ($_GET["page"] == "openai-panel_help"))) {
67 add_action('admin_enqueue_scripts', array($this, 'qcld_wb_chatbot_admin_scripts'));
68 }
69
70
71 }
72
73
74 /**
75 * Define wpbot Constants.
76 *
77 * @return void
78 * @since 1.0.0
79 */
80 public function define_constants() {
81 if( ! defined( 'QCLD_openai_addon_VERSION' ) ){
82 define('QCLD_openai_addon_VERSION', $this->version);
83 }
84 //define('QCLD_openai_addon_REQUIRED_wpCOMMERCE_VERSION', 2.2);
85
86 if( ! defined( 'QCLD_openai_addon_PLUGIN_DIR_PATH' ) ){
87 define('QCLD_openai_addon_PLUGIN_DIR_PATH', plugin_dir_path(__FILE__));
88 }
89 if( ! defined( 'QCLD_openai_addon_PLUGIN_URL' ) ){
90 define('QCLD_openai_addon_PLUGIN_URL', plugin_dir_url(__FILE__));
91 }
92 if( ! defined( 'QCLD_openai_addon_IMG_URL' ) ){
93 define('QCLD_openai_addon_IMG_URL', QCLD_openai_addon_PLUGIN_URL . "images/");
94 }
95 if( ! defined( 'QCLD_openai_addon_IMG_ABSOLUTE_PATH' ) ){
96 define('QCLD_openai_addon_IMG_ABSOLUTE_PATH', plugin_dir_path(__FILE__) . "images");
97 }
98
99 }
100
101
102 public function qcld_wb_chatbot_admin_scripts(){
103 // wp_register_style('qlcd-open-ai-bootstap', QCLD_openai_addon_PLUGIN_URL . 'css/openai-bootstrap.css', '', QCLD_openai_addon_VERSION, 'screen');
104 // wp_enqueue_style('qlcd-open-ai-bootstap');
105 // wp_register_style('qlcd-open-ai-admin-style', QCLD_openai_addon_PLUGIN_URL . 'css/openai-admin-style.css', '', QCLD_openai_addon_VERSION, 'screen');
106 // wp_enqueue_style('qlcd-open-ai-admin-style');
107 // wp_register_script('qlcd-openai_collapse', QCLD_openai_addon_PLUGIN_URL . 'js/collapse.js', array('jquery'),'',QCLD_openai_addon_VERSION,true);
108 // wp_enqueue_script('qlcd-openai_collapse');
109 // wp_register_script('qlcd-openai_settings', QCLD_openai_addon_PLUGIN_URL . 'js/openai_settings.js', array('jquery'),'',QCLD_openai_addon_VERSION,true);
110 // wp_enqueue_script('qlcd-openai_settings');
111
112 // wp_localize_script( 'qlcd-openai_settings', 'openai_ajax', array(
113 // 'url' => admin_url( 'admin-ajax.php' ),
114 // ) );
115
116 }
117 /**
118 * Include all required files
119 *
120 * since 1.0.0
121 *
122 * @return void
123 */
124 public function includes() {
125 require_once( QCLD_wpCHATBOT_PLUGIN_DIR_PATH . "includes/openai/qcld_wp_OpenAI.php" );
126 require_once( QCLD_wpCHATBOT_PLUGIN_DIR_PATH . "includes/openai/OpenAi_WPBot_Menu.php" );
127 require_once( QCLD_wpCHATBOT_PLUGIN_DIR_PATH . "includes/openai/Parsedown.php" );
128
129 }
130 // public function openai_file_delete_callback(){
131 // $file_id = sanitize_text_field($_POST['file_id']);
132 // $url = 'https://api.openai.com/v1/files/'. $file_id;
133 // $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
134 // $ch = curl_init();
135 // curl_setopt($ch, CURLOPT_URL, $url);
136 // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
137 // curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
138 // $headers = array(
139 // $apt_key,
140 // );
141 // curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
142 // $result = curl_exec($ch);
143 // if (curl_errno($ch)) {
144 // echo 'Error:' . curl_error($ch);
145 // }
146 // curl_close($ch);
147 // wp_send_json( json_decode($result));
148 // wp_die();
149 // }
150
151 public function buildFormBody( $fields, $boundary )
152 {
153 $body = '';
154 foreach ( $fields as $name => $value ) {
155 if ( $name == 'data' ) {
156 continue;
157 }
158 $body .= "--$boundary\r\n";
159 $body .= "Content-Disposition: form-data; name=\"$name\"";
160 if ( $name == 'file' ) {
161 $body .= "; filename=\"{$value}\"\r\n";
162 $body .= "Content-Type: application/json\r\n\r\n";
163 $body .= $fields['data'] . "\r\n";
164 }else {
165 $body .= "\r\n\r\n$value\r\n";
166 }
167 }
168 $body .= "--$boundary--\r\n";
169 return $body;
170 }
171
172 // public function openai_file_list_callback(){
173 // $url = 'https://api.openai.com/v1/files';
174 // $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
175 // $curl = curl_init();
176 // curl_setopt($curl, CURLOPT_URL, $url);
177 // $headers = array(
178 // "Content-Type: application/json",
179 // $apt_key,
180 // );
181 // curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
182 // curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
183 // $response = curl_exec($curl);
184 // curl_close($curl);
185 // wp_send_json( json_decode($response));
186 // wp_die();
187 // }
188 public function qcld_sanitize_text_or_array_field($array_or_string) {
189 if( is_string($array_or_string) ){
190 $array_or_string = sanitize_text_field($array_or_string);
191 }elseif( is_array($array_or_string) ){
192 foreach ( $array_or_string as $key => &$value ) {
193 if ( is_array( $value ) ) {
194 $value = $this->sanitize_text_or_array_field($value);
195 }
196 else {
197 $value = sanitize_text_field( $value );
198 }
199 }
200 }
201
202 return $array_or_string;
203 }
204
205 // public function openai_file_upload_callback(){
206 // $uploadedfile = $_FILES['file'];
207 // $url = 'https://api.openai.com/v1/files';
208 // $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
209 // $curl = curl_init($url);
210 // curl_setopt($curl, CURLOPT_URL, $url);
211 // curl_setopt($curl, CURLOPT_POST, true);
212 // $headers = array(
213 // "Content-Type: multipart/form-data",
214 // $apt_key,
215 // );
216 // if (function_exists('curl_file_create')) {
217 // $tmp_file = curl_file_create($uploadedfile['tmp_name'], 'jsonl', $uploadedfile['name']);
218 // } else {
219 // $tmp_file = open($uploadedfile['tmp_name']);
220 // }
221 // $data = array('file'=> $tmp_file,'purpose'=> 'fine-tune');
222 // $init = curl_init();
223 // //function parameteres
224 // curl_setopt($init, CURLOPT_URL,$url);
225 // curl_setopt($init, CURLOPT_HTTPHEADER, $headers);
226 // curl_setopt($init, CURLOPT_POSTFIELDS, $data);
227 // curl_setopt($init, CURLOPT_RETURNTRANSFER, true);
228 // $res = json_decode(curl_exec ($init));
229
230 // curl_close ($init);
231 // if(!empty($res->error)){
232 // $response['status'] = 'error';
233 // $response['message'] = $res->error->message;
234 // }
235
236 // if(!empty($res->status)){
237 // $response['status'] = 'success';
238 // $response['message'] = 'Successfully Created file' . $res->id ;
239
240 // }
241 // echo wp_send_json([$response]);
242 // wp_die();
243 // }
244 public function openai_finetune_create($file_id,$ft_suffix,$ft_engines){
245 $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
246 $headers = array(
247 "Content-Type: application/json",
248 $apt_key,
249 );
250 $curl = curl_init();
251 $qcld_openai_suffix = isset($ft_suffix) ? $ft_suffix : get_option('qcld_openai_suffix');
252 $openai_engines = isset($ft_engines) ? $ft_engines : get_option('openai_engines');
253 $base_engine = explode('-',$openai_engines);
254 if( $base_engine[0] == 'gpt'){
255 $data = json_encode(array('training_file'=>$file_id,'model' => $openai_engines, 'suffix' => $qcld_openai_suffix ));
256 $url = "https://api.openai.com/v1/fine_tuning/jobs";
257 curl_setopt($curl, CURLOPT_URL, $url);
258 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
259 curl_setopt($curl, CURLOPT_POST, true);
260 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
261 curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
262 $result = json_decode(curl_exec($curl));
263 curl_close($curl);
264 }else{
265
266 $data = json_encode(array('training_file'=>$file_id,'model' => $base_engine[1], 'suffix' => $qcld_openai_suffix ));
267 $url = "https://api.openai.com/v1/fine-tunes";
268 curl_setopt($curl, CURLOPT_URL, $url);
269 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
270 curl_setopt($curl, CURLOPT_POST, true);
271 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
272 curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
273 $result = json_decode(curl_exec($curl));
274 curl_close($curl);
275 }
276 return $result;
277 }
278 public function relevant_pagelink($search_query){
279
280 $stopwords = explode( ',', get_option('qlcd_wp_chatbot_stop_words') );
281
282 $finalQueryWordsWithoutStopWords = $this->qcpd_remove_wa_stopwords( strtolower($search_query), $stopwords );
283
284 $cleanWordsWithoutPunctuationMarks = preg_replace('/[\p{P}]/u', '', $finalQueryWordsWithoutStopWords);
285
286 $q = trim($cleanWordsWithoutPunctuationMarks);
287
288 $links = [];
289
290 $post_type_array = ['post','page'];
291
292 //Proceeding with traditional search
293
294 $the_query = new WP_Query( array( 'post_status' => 'publish', 'posts_per_page' => 5, 's' => esc_attr( $q ), 'post_type' => $post_type_array ) );
295
296 if( $the_query->have_posts() ){
297
298 while( $the_query->have_posts() ){
299
300 $the_query->the_post();
301
302 $url = esc_url( get_permalink() );
303
304 $link = '<li><mark><a style="color: #000" href=' . $url . '>' . get_the_title() . '</a><mark></li>';
305
306 array_push($links, $link);
307
308 } //End of WHILE
309
310 wp_reset_postdata();
311
312 } //End of IF
313
314 $links = array_unique($links);
315
316 return $links;
317
318 } //End of function relevant_pagelink()
319 public function openai_retrive_fine_tune($keyword){
320
321 $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
322 $headers = array(
323 "Content-Type: application/json",
324 $apt_key,
325 );
326 $curl = curl_init();
327 $max_tokens = (int)get_option( 'openai_max_tokens');
328 $temp = (float)get_option( 'openai_temperature');
329 $frequency_penalty = (float)get_option( 'frequency_penalty');
330 $presence_penalty = (float)get_option( 'presence_penalty');
331 $engines = explode('-',get_option( 'openai_engines'));
332 $custom_model = get_option( 'qcld_openai_custom_model');
333 $custom_model = (explode(":",$custom_model));
334 $prompts = $this->get_prompt($keyword);
335
336 if($custom_model[1] != 'gpt-3.5-turbo-0613'){
337 $data = json_encode(array(
338 'prompt'=> $prompts,
339 'model'=> get_option( 'qcld_openai_custom_model'),
340 "max_tokens" => $max_tokens,
341 "temperature" => $temp,
342 "top_p" => 1,
343 "presence_penalty" => $frequency_penalty,
344 "frequency_penalty"=> $presence_penalty,
345 "best_of"=> 1,
346 "stop"=> ["\n###\n","###"]
347 ));
348 $url = "https://api.openai.com/v1/completions";
349
350 $ch = curl_init();
351
352 curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/completions');
353 // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
354 // curl_setopt($ch, CURLOPT_POST, 1);
355 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
356 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
357 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
358 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
359
360 $result = (curl_exec($ch));
361 $result = str_replace("#","",$result );
362
363 return $result;
364 if (curl_errno($ch)) {
365 // phpcs:ignore
366 echo 'Error:' . curl_error($ch);
367 }
368 curl_close($ch);
369 }else{
370 $data = json_encode(array(
371 'model'=> get_option( 'qcld_openai_custom_model'),
372 "messages"=> [
373
374 [
375 "role"=> "user",
376 "content"=>$keyword
377 ]
378
379 ],
380
381 ));
382 $ch = curl_init();
383
384 curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
385 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
386 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
387 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
388 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
389
390 $results = (curl_exec($ch));
391 $results = str_replace("#","",$result );
392 $result = (json_decode($results)->choices[0]->message->content);
393 return $result;
394
395
396 }
397
398 }
399 public function response_form_file($keyword){
400 $max_tokens = (int)get_option( 'openai_max_tokens');
401 $temp = (float)get_option( 'openai_temperature');
402 $frequency_penalty = (float)get_option( 'frequency_penalty');
403 $presence_penalty = (float)get_option( 'presence_penalty');
404 $engines = explode('-',get_option( 'openai_engines'));
405 if($engines[0] != 'gpt'){
406 // $prompts = $this->get_prompt($keyword);
407 }
408
409 $request_body = [
410 "prompt" => $keyword,
411 "model" => get_option( 'qcld_openai_custom_model'),
412 "max_tokens" => $max_tokens,
413 "temperature" => 0,
414 "top_p" => 1,
415 "stop" => [],
416 "presence_penalty" => 0,
417 "frequency_penalty"=> 0,
418 "best_of"=> 1,
419 ];
420 $postFields = json_encode($request_body);
421 $OpenAI = new qcld_wp_OpenAI();
422 $result = $OpenAI->get_response($postFields);
423
424 return $result;
425 }
426 public function get_prompt($keyword){
427 $openai_include_keyword = get_option( 'openai_include_keyword');
428 $openai_exclude_keyword = get_option( 'openai_exclude_keyword');
429 $qcld_openai_prompt = get_option('qcld_openai_prompt',true);
430
431 }
432 public function include_exclude_prompt($keyword){
433 $openai_include_keyword = strtolower(get_option('openai_include_keyword'));
434 $openai_exclude_keyword = strtolower(get_option('openai_exclude_keyword'));
435
436 if((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') == '')){
437 $prompts = 'If the query is not relevant to one of the keywords: '.$openai_include_keyword .' then only say DUH. Provide a response only if the following query is relevant to one of the keywords: '.$openai_include_keyword .' The actual query is as follows: '. $keyword;
438 return $prompts;
439 }else if((get_option('openai_include_keyword') == '') || (get_option('openai_exclude_keyword') != '')){
440
441 $prompts = 'If the query is relevant to one of the keywords: ' .$openai_exclude_keyword . ', then do not respond and only say "DUH." The actual query is as follows: '. $keyword. '?/n';
442 return $prompts;
443 }else if((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')){
444 $prompts = 'If the query is not relevant to one of the keywords: '.$openai_include_keyword .' then only say "DUH." Provide a response only if the following query is relevant to one of the keywords: '.$openai_include_keyword .' The actual query is as follows: '. $keyword;
445 return $prompts;
446 }
447 }
448 public function qcld_include_keyword_exist( $keyword ){
449 $keyword = isset($keyword) ? $keyword : '';
450 $openai_include_keywords = strtolower(get_option('openai_include_keyword'));
451 if(!empty($keyword)){
452 $openai_include_keyword = ( isset( $openai_include_keywords ) ? $openai_include_keywords : '');
453
454 if( !empty($openai_include_keyword)){
455 $include_items = explode(',', $openai_include_keyword);
456 if(!empty($include_items)){
457 foreach($include_items as $k => $item){
458 if((strpos($keyword,trim($item)) !== false) && !empty($item)){
459 return true;
460 }
461 }
462 }
463 return false;
464 }
465 }
466
467 return false;
468
469 }
470 public function openai_response_callback() {
471 // $nonce = sanitize_text_field($_POST['nonce']);
472 // if (! wp_verify_nonce($nonce,'qcsecretbotnonceval123qc')) {
473 // wp_send_json(array('success' => false, 'msg' => esc_html__('Failed in Security check', 'sm')));
474 // wp_die();
475
476 // }else{
477 $response['status'] = 'success';
478 $response['message'] ='A preset message';
479 $OpenAI = new qcld_wp_OpenAI();
480 $gptkeyword = [];
481 $keyword = sanitize_text_field($_POST['keyword']);
482 $relevant_pagelink = $this->relevant_pagelink($keyword);
483
484 $relevant_pagelink = array_slice($relevant_pagelink, 0, 5, true);
485
486 if( (get_option('page_suggestion_enabled') == '1') && count($relevant_pagelink) > 0 ){
487
488 $relevant_post_link = get_option('qlcd_wp_chatbot_relevant_post_link_openai');
489
490 if(is_array($relevant_post_link )){
491
492 $relevant_pagelinks = '<br><br><p><em>'. implode('', $relevant_post_link) .'</em></p><ul style="list-style: disc;padding-left: 10px;">'. implode(" ", $relevant_pagelink). '</ul>';
493 }else{
494 $relevant_pagelinks = '<br><br><p><em>'. $relevant_post_link .'</em></p><ul style="list-style: disc;padding-left: 10px;">'. implode(" ", $relevant_pagelink) .'</ul>';
495 }
496 }else{
497 $relevant_pagelinks = '';
498 }
499 if(get_option( 'is_asst_enabled') != 1){
500 $response_files = $this->openai_retrive_fine_tune($keyword);
501 $response_file = json_decode($response_files, true);
502 $gptkeywords = [];
503 if((empty($response_file['choices'][0]["text"])) && empty($response_file['choices'][0]["message"]['content'])){
504 array_push( $gptkeyword, array(
505 "role" => "system",
506 "content" => get_option('qcld_openai_system_content')
507 ));
508 array_push($gptkeyword, array(
509 "role" => "user",
510 "content" => $keyword
511 ));
512 if(((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')) && (get_option('qcld_openai_relevant_enabled') == '1') ){
513 $prompts = $this->include_exclude_prompt($keyword);
514
515 $gptkeyword = [];
516 array_push($gptkeyword, array(
517 "role" => "user",
518 "content" => $prompts,
519 ));
520 }else if(((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')) && (get_option('qcld_openai_relevant_enabled') == '0')){
521 if($this->qcld_include_keyword_exist($keyword) == false){
522
523 $response['message'] = 'Sorry, No result found!';
524 echo json_encode($response);
525 wp_die();
526 }else{
527 array_push($gptkeyword, array(
528 "role" => "user",
529 "content" => $keyword
530 ));
531 }
532
533 }
534 $res = $OpenAI->gptcomplete(
535 $gptkeyword
536 );
537 $mess = json_decode($res);
538
539 $Parsedown = new Parsedown();
540 $msg = $mess->output[0]->content[0]->text;
541 $msg = $Parsedown->text($msg);
542 $response['message'] = $msg ;
543 if(($response['message'] == 'DUH.') || ($response['message'] == 'DUH')){
544 $response['message'] = 'Sorry, No result found!';
545 }else{
546 $Parsedown = new Parsedown();
547 $msg = $mess->output[0]->content[0]->text;
548 $msg = $Parsedown->text($msg);
549 $response['message'] = $msg . $relevant_pagelinks;
550 }
551 }else if(!empty($response_file['choices'][0]["message"]['content'])){
552 $result = $response_file['choices'][0]["message"]['content'];
553 $Parsedown = new Parsedown();
554 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$result);
555 $response['message'] = $msg . $relevant_pagelinks;
556 }else{
557 $result = $response_file['choices'][0]["text"];
558 $message = explode(">",$result);
559 if(empty($message)){
560 $message = $result;
561 }elseif(empty($message[1])){
562 $message = $message[0];
563 }else{
564 $message = $message[1];
565 }
566 $Parsedown = new Parsedown();
567 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$message);
568 $message = $Parsedown->text($msg);
569 if(get_option('conversation_continuity') == 1){
570 $lasfivecookie = $_COOKIE["last_five_prompt"] . $message . '###';
571 setcookie('last_five_prompt', $lasfivecookie, time() + (60000), "/");
572 $response['cookie'] = $lasfivecookie;
573 }
574 $response['message'] = $message . $relevant_pagelinks;
575 }
576 }else{
577 $url = 'https://api.openai.com/v1/threads';
578 $api_key = get_option('open_ai_api_key');
579 $engines = get_option( 'openai_engines');
580
581 $header = [
582 'Content-Type: application/json',
583 'OpenAI-Beta: assistants=v1',
584 'Authorization: Bearer ' . $api_key
585 ];
586 // $threads_id = '';
587 $threads_id_COOKIE = $_COOKIE["qcld_threads_id"];
588 $threads_id = $threads_id_COOKIE;
589 if(($threads_id == '')){
590
591 $ch = curl_init();
592 curl_setopt($ch, CURLOPT_URL, $url);
593 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
594 curl_setopt($ch, CURLOPT_POST, 1);
595 // curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));
596 curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
597 $threads = curl_exec($ch);
598 $threads_id = json_decode($threads)->id;
599 setcookie('qcld_threads_id',$threads_id , time() + (60000), "/");
600 if (curl_errno($ch)) {
601 // phpcs:ignore
602 echo 'Error: ' . curl_error($ch);
603 }
604 curl_close($ch);
605 }
606
607 $msg = $this->add_on_thrrads($threads_id,$keyword);
608 $Parsedown = new Parsedown();
609 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$msg);
610 $message = $Parsedown->text($msg);
611 $response['message'] = $message . $relevant_pagelinks;
612
613 }
614 echo json_encode($response);
615 wp_die();
616 //}
617 }
618 public function openai_settings_option_callback() {
619 $nonce = sanitize_text_field($_POST['nonce']);
620
621 if (! wp_verify_nonce($nonce,'wp_chatbot')) {
622 wp_send_json(array('success' => false, 'msg' => esc_html__('Failed in Security check', 'sm')));
623 wp_die();
624
625 }else{
626
627 $api_key = sanitize_text_field($_POST['api_key']);
628 $openai_engines = sanitize_text_field($_POST['openai_engines']);
629 $qcld_openai_prompt = sanitize_text_field($_POST['qcld_openai_prompt']);
630 $max_tokens = sanitize_text_field($_POST['max_tokens']);
631 $qcld_openai_suffix = (!empty($_POST['qcld_openai_suffix'])) ? sanitize_text_field($_POST['qcld_openai_suffix']) : '';
632 $qcld_openai_custom_model = sanitize_text_field($_POST['qcld_openai_custom_model']);
633 $frequency_penalty = sanitize_text_field($_POST['frequency_penalty']);
634 $presence_penalty = sanitize_text_field($_POST['presence_penalty']);
635 $temperature = sanitize_text_field($_POST['temperature']);
636 $ai_enabled = sanitize_text_field($_POST['ai_enabled']);
637 $suggestion_enabled = sanitize_text_field($_POST['is_page_suggestion_enabled']);
638 $is_relevant_enabled = sanitize_text_field($_POST['is_relevant_enabled']);
639 $file_id = (!empty($_POST['file_id'])) ? sanitize_text_field($_POST['file_id']) : '';
640 $qcld_openai_prompt_custom = sanitize_text_field($_POST['qcld_openai_prompt_custom']);
641 $conversation_continuity = sanitize_text_field($_POST['conversation_continuity']);
642 $qcld_openai_system_content = sanitize_text_field($_POST['qcld_openai_system_content']);
643 /* Customized by Kadir on 05-12-2023 : To set empty value for API field */
644
645 $disable_ss = sanitize_text_field($_POST['disable_ss']);
646
647 if($api_key != ''){
648 update_option( 'open_ai_api_key', $api_key );
649 }
650 else{
651 delete_option( 'open_ai_api_key');
652 }
653
654 /* Ends: Customized by Kadir on 05-12-2023 : To set empty value for API field */
655
656 if($openai_engines != ''){
657 update_option( 'openai_engines', $openai_engines );
658 }
659 if($conversation_continuity != ''){
660 update_option( 'conversation_continuity', $conversation_continuity );
661 }
662 update_option( 'openai_max_tokens', $max_tokens );
663
664 if($qcld_openai_suffix != ''){
665 update_option('qcld_openai_suffix', $qcld_openai_suffix);
666 }
667 if($frequency_penalty != ''){
668 update_option( 'frequency_penalty', $frequency_penalty );
669 }
670 if($presence_penalty != ''){
671 update_option( 'presence_penalty', $presence_penalty );
672 }
673 if($temperature != ''){
674 update_option( 'openai_temperature', $temperature );
675 }
676 if($qcld_openai_prompt_custom != ''){
677 update_option('qcld_openai_prompt_custom', $qcld_openai_prompt_custom );
678 }
679 update_option('qcld_openai_custom_model',$qcld_openai_custom_model);
680 update_option('qcld_openai_system_content', stripslashes( $qcld_openai_system_content));
681 update_option('ai_enabled',$ai_enabled);
682 update_option('qcld_openai_relevant_enabled',$is_relevant_enabled);
683 update_option('page_suggestion_enabled',$suggestion_enabled);
684 if($file_id != ''){
685 update_option('file_id',$file_id);
686 }
687 $openai_include_keyword = sanitize_text_field($_POST['openai_include_keyword']);
688 update_option('openai_include_keyword',$openai_include_keyword);
689 $openai_exclude_keyword = sanitize_text_field($_POST['openai_exclude_keyword']);
690 update_option('openai_exclude_keyword',$openai_exclude_keyword);
691
692
693 /* Customized by Kadir on 05-12-2023 : To Disable Site Search*/
694 //Disable Site Search
695 if( $disable_ss == 1 ){
696 update_option('disable_wp_chatbot_site_search',1);
697 }
698 /* Ends: Customized by Kadir on 05-12-2023 : To Disable Site Search*/
699
700
701
702 }
703 if($qcld_openai_prompt != ''){
704 update_option('qcld_openai_prompt', $qcld_openai_prompt);
705 }
706 $tem = get_option( 'openai_temperature', $temperature );
707
708 echo json_encode($ai_enabled);wp_die();
709
710 }
711 public function qcpd_remove_wa_stopwords($query, $stopwords){
712
713 return preg_replace('/\b('.implode('|',$stopwords).')\b/','',$query);
714
715 }
716 public function openai_troubleshooting(){
717 $nonce = sanitize_text_field($_POST['nonce']);
718 $OpenAI = new qcld_wp_OpenAI();
719 if (! wp_verify_nonce($nonce,'wp_chatbot')) {
720 wp_send_json(array('success' => false, 'msg' => esc_html__('Failed in Security check', 'sm')));
721 wp_die();
722
723 }else{
724 $gptkeyword = [];
725 array_push($gptkeyword, array(
726 "role" => "user",
727 "content" => "Is our request comes from openAI ?"
728 ));
729 $res = $OpenAI->gptcomplete(
730 $gptkeyword
731 );
732 if(empty(json_decode($res)->error)){
733 $mess = json_decode($res);
734 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$mess->choices[0]->message->content);
735 wp_send_json(array('success' => true,'title' => esc_html__('success', 'sm'),'icon'=>esc_html__('alert-success', 'sm'),'msg' => esc_html__($msg, 'sm')));
736 }else{
737
738 wp_send_json(array('success' => true,'title' => esc_html__('Error', 'sm'),'icon'=>esc_html__('error', 'sm'), 'msg' => esc_html__(json_decode($res)->error->message, 'sm')));
739 }
740 }
741 }
742
743
744 }
745
746 /**
747 * @return qcld_wpopenai_addon
748 */
749 if(!function_exists('qcld_wpopenai_addons')){
750 function qcld_openais() {
751 $qcld_wpopenai_addon = new qcld_wpopenai_addons();
752 return $qcld_wpopenai_addon->instance();
753
754 }
755 }
756
757 //fire off the plugin
758 qcld_openais();
759
760 }