PluginProbe
WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services / 6.0.0
WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services v6.0.0
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 8.5.2 All 533 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.0.0, at includes/openai/qcld-bot-openai.php

759 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 $Parsedown = new Parsedown();
539 $msg = $mess->choices[0]->message->content;
540 $msg = $Parsedown->text($msg);
541 $response['message'] = $msg ;
542 if(($response['message'] == 'DUH.') || ($response['message'] == 'DUH')){
543 $response['message'] = 'Sorry, No result found!';
544 }else{
545 $Parsedown = new Parsedown();
546 $msg = $mess->choices[0]->message->content;
547 $msg = $Parsedown->text($msg);
548 $response['message'] = $msg . $relevant_pagelinks;
549 }
550 }else if(!empty($response_file['choices'][0]["message"]['content'])){
551 $result = $response_file['choices'][0]["message"]['content'];
552 $Parsedown = new Parsedown();
553 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$result);
554 $response['message'] = $msg . $relevant_pagelinks;
555 }else{
556 $result = $response_file['choices'][0]["text"];
557 $message = explode(">",$result);
558 if(empty($message)){
559 $message = $result;
560 }elseif(empty($message[1])){
561 $message = $message[0];
562 }else{
563 $message = $message[1];
564 }
565 $Parsedown = new Parsedown();
566 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$message);
567 $message = $Parsedown->text($msg);
568 if(get_option('conversation_continuity') == 1){
569 $lasfivecookie = $_COOKIE["last_five_prompt"] . $message . '###';
570 setcookie('last_five_prompt', $lasfivecookie, time() + (60000), "/");
571 $response['cookie'] = $lasfivecookie;
572 }
573 $response['message'] = $message . $relevant_pagelinks;
574 }
575 }else{
576 $url = 'https://api.openai.com/v1/threads';
577 $api_key = get_option('open_ai_api_key');
578 $engines = get_option( 'openai_engines');
579
580 $header = [
581 'Content-Type: application/json',
582 'OpenAI-Beta: assistants=v1',
583 'Authorization: Bearer ' . $api_key
584 ];
585 // $threads_id = '';
586 $threads_id_COOKIE = $_COOKIE["qcld_threads_id"];
587 $threads_id = $threads_id_COOKIE;
588 if(($threads_id == '')){
589
590 $ch = curl_init();
591 curl_setopt($ch, CURLOPT_URL, $url);
592 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
593 curl_setopt($ch, CURLOPT_POST, 1);
594 // curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));
595 curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
596 $threads = curl_exec($ch);
597 $threads_id = json_decode($threads)->id;
598 setcookie('qcld_threads_id',$threads_id , time() + (60000), "/");
599 if (curl_errno($ch)) {
600 // phpcs:ignore
601 echo 'Error: ' . curl_error($ch);
602 }
603 curl_close($ch);
604 }
605
606 $msg = $this->add_on_thrrads($threads_id,$keyword);
607 $Parsedown = new Parsedown();
608 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$msg);
609 $message = $Parsedown->text($msg);
610 $response['message'] = $message . $relevant_pagelinks;
611
612 }
613 echo json_encode($response);
614 wp_die();
615 //}
616 }
617 public function openai_settings_option_callback() {
618 $nonce = sanitize_text_field($_POST['nonce']);
619
620 if (! wp_verify_nonce($nonce,'wp_chatbot')) {
621 wp_send_json(array('success' => false, 'msg' => esc_html__('Failed in Security check', 'sm')));
622 wp_die();
623
624 }else{
625
626 $api_key = sanitize_text_field($_POST['api_key']);
627 $openai_engines = sanitize_text_field($_POST['openai_engines']);
628 $qcld_openai_prompt = sanitize_text_field($_POST['qcld_openai_prompt']);
629 $max_tokens = sanitize_text_field($_POST['max_tokens']);
630 $qcld_openai_suffix = (!empty($_POST['qcld_openai_suffix'])) ? sanitize_text_field($_POST['qcld_openai_suffix']) : '';
631 $qcld_openai_custom_model = sanitize_text_field($_POST['qcld_openai_custom_model']);
632 $frequency_penalty = sanitize_text_field($_POST['frequency_penalty']);
633 $presence_penalty = sanitize_text_field($_POST['presence_penalty']);
634 $temperature = sanitize_text_field($_POST['temperature']);
635 $ai_enabled = sanitize_text_field($_POST['ai_enabled']);
636 $suggestion_enabled = sanitize_text_field($_POST['is_page_suggestion_enabled']);
637 $is_relevant_enabled = sanitize_text_field($_POST['is_relevant_enabled']);
638 $file_id = (!empty($_POST['file_id'])) ? sanitize_text_field($_POST['file_id']) : '';
639 $qcld_openai_prompt_custom = sanitize_text_field($_POST['qcld_openai_prompt_custom']);
640 $conversation_continuity = sanitize_text_field($_POST['conversation_continuity']);
641 $qcld_openai_system_content = sanitize_text_field($_POST['qcld_openai_system_content']);
642 /* Customized by Kadir on 05-12-2023 : To set empty value for API field */
643
644 $disable_ss = sanitize_text_field($_POST['disable_ss']);
645
646 if($api_key != ''){
647 update_option( 'open_ai_api_key', $api_key );
648 }
649 else{
650 delete_option( 'open_ai_api_key');
651 }
652
653 /* Ends: Customized by Kadir on 05-12-2023 : To set empty value for API field */
654
655 if($openai_engines != ''){
656 update_option( 'openai_engines', $openai_engines );
657 }
658 if($conversation_continuity != ''){
659 update_option( 'conversation_continuity', $conversation_continuity );
660 }
661 update_option( 'openai_max_tokens', $max_tokens );
662
663 if($qcld_openai_suffix != ''){
664 update_option('qcld_openai_suffix', $qcld_openai_suffix);
665 }
666 if($frequency_penalty != ''){
667 update_option( 'frequency_penalty', $frequency_penalty );
668 }
669 if($presence_penalty != ''){
670 update_option( 'presence_penalty', $presence_penalty );
671 }
672 if($temperature != ''){
673 update_option( 'openai_temperature', $temperature );
674 }
675 if($qcld_openai_prompt_custom != ''){
676 update_option('qcld_openai_prompt_custom', $qcld_openai_prompt_custom );
677 }
678 update_option('qcld_openai_custom_model',$qcld_openai_custom_model);
679 update_option('qcld_openai_system_content', stripslashes( $qcld_openai_system_content));
680 update_option('ai_enabled',$ai_enabled);
681 update_option('qcld_openai_relevant_enabled',$is_relevant_enabled);
682 update_option('page_suggestion_enabled',$suggestion_enabled);
683 if($file_id != ''){
684 update_option('file_id',$file_id);
685 }
686 $openai_include_keyword = sanitize_text_field($_POST['openai_include_keyword']);
687 update_option('openai_include_keyword',$openai_include_keyword);
688 $openai_exclude_keyword = sanitize_text_field($_POST['openai_exclude_keyword']);
689 update_option('openai_exclude_keyword',$openai_exclude_keyword);
690
691
692 /* Customized by Kadir on 05-12-2023 : To Disable Site Search*/
693 //Disable Site Search
694 if( $disable_ss == 1 ){
695 update_option('disable_wp_chatbot_site_search',1);
696 }
697 /* Ends: Customized by Kadir on 05-12-2023 : To Disable Site Search*/
698
699
700
701 }
702 if($qcld_openai_prompt != ''){
703 update_option('qcld_openai_prompt', $qcld_openai_prompt);
704 }
705 $tem = get_option( 'openai_temperature', $temperature );
706
707 echo json_encode($ai_enabled);wp_die();
708
709 }
710 public function qcpd_remove_wa_stopwords($query, $stopwords){
711
712 return preg_replace('/\b('.implode('|',$stopwords).')\b/','',$query);
713
714 }
715 public function openai_troubleshooting(){
716 $nonce = sanitize_text_field($_POST['nonce']);
717 $OpenAI = new qcld_wp_OpenAI();
718 if (! wp_verify_nonce($nonce,'wp_chatbot')) {
719 wp_send_json(array('success' => false, 'msg' => esc_html__('Failed in Security check', 'sm')));
720 wp_die();
721
722 }else{
723 $gptkeyword = [];
724 array_push($gptkeyword, array(
725 "role" => "user",
726 "content" => "Is our request comes from openAI ?"
727 ));
728 $res = $OpenAI->gptcomplete(
729 $gptkeyword
730 );
731 if(empty(json_decode($res)->error)){
732 $mess = json_decode($res);
733 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$mess->choices[0]->message->content);
734 wp_send_json(array('success' => true,'title' => esc_html__('success', 'sm'),'icon'=>esc_html__('alert-success', 'sm'),'msg' => esc_html__($msg, 'sm')));
735 }else{
736
737 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')));
738 }
739 }
740 }
741
742
743 }
744
745 /**
746 * @return qcld_wpopenai_addon
747 */
748 if(!function_exists('qcld_wpopenai_addons')){
749 function qcld_openais() {
750 $qcld_wpopenai_addon = new qcld_wpopenai_addons();
751 return $qcld_wpopenai_addon->instance();
752
753 }
754 }
755
756 //fire off the plugin
757 qcld_openais();
758
759 }