PluginProbe
WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services / 8.0.0
WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services v8.0.0
8.8.4 8.8.3 8.8.2 8.8.1 8.8.0 8.7.9 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 All 540 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 8.0.0, at includes/openai/qcld-bot-openai.php

743 lines 34.6 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
131 public function buildFormBody( $fields, $boundary )
132 {
133 $body = '';
134 foreach ( $fields as $name => $value ) {
135 if ( $name == 'data' ) {
136 continue;
137 }
138 $body .= "--$boundary\r\n";
139 $body .= "Content-Disposition: form-data; name=\"$name\"";
140 if ( $name == 'file' ) {
141 $body .= "; filename=\"{$value}\"\r\n";
142 $body .= "Content-Type: application/json\r\n\r\n";
143 $body .= $fields['data'] . "\r\n";
144 }else {
145 $body .= "\r\n\r\n$value\r\n";
146 }
147 }
148 $body .= "--$boundary--\r\n";
149 return $body;
150 }
151
152 // public function openai_file_list_callback(){
153 // $url = 'https://api.openai.com/v1/files';
154 // $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
155 // $curl = curl_init();
156 // curl_setopt($curl, CURLOPT_URL, $url);
157 // $headers = array(
158 // "Content-Type: application/json",
159 // $apt_key,
160 // );
161 // curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
162 // curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
163 // $response = curl_exec($curl);
164 // curl_close($curl);
165 // wp_send_json( json_decode($response));
166 // wp_die();
167 // }
168 public function qcld_sanitize_text_or_array_field($array_or_string) {
169 if( is_string($array_or_string) ){
170 $array_or_string = sanitize_text_field($array_or_string);
171 }elseif( is_array($array_or_string) ){
172 foreach ( $array_or_string as $key => &$value ) {
173 if ( is_array( $value ) ) {
174 $value = $this->sanitize_text_or_array_field($value);
175 }
176 else {
177 $value = sanitize_text_field( $value );
178 }
179 }
180 }
181
182 return $array_or_string;
183 }
184
185 // public function openai_file_upload_callback(){
186 // $uploadedfile = $_FILES['file'];
187 // $url = 'https://api.openai.com/v1/files';
188 // $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
189 // $curl = curl_init($url);
190 // curl_setopt($curl, CURLOPT_URL, $url);
191 // curl_setopt($curl, CURLOPT_POST, true);
192 // $headers = array(
193 // "Content-Type: multipart/form-data",
194 // $apt_key,
195 // );
196 // if (function_exists('curl_file_create')) {
197 // $tmp_file = curl_file_create($uploadedfile['tmp_name'], 'jsonl', $uploadedfile['name']);
198 // } else {
199 // $tmp_file = open($uploadedfile['tmp_name']);
200 // }
201 // $data = array('file'=> $tmp_file,'purpose'=> 'fine-tune');
202 // $init = curl_init();
203 // //function parameteres
204 // curl_setopt($init, CURLOPT_URL,$url);
205 // curl_setopt($init, CURLOPT_HTTPHEADER, $headers);
206 // curl_setopt($init, CURLOPT_POSTFIELDS, $data);
207 // curl_setopt($init, CURLOPT_RETURNTRANSFER, true);
208 // $res = json_decode(curl_exec ($init));
209
210 // curl_close ($init);
211 // if(!empty($res->error)){
212 // $response['status'] = 'error';
213 // $response['message'] = $res->error->message;
214 // }
215
216 // if(!empty($res->status)){
217 // $response['status'] = 'success';
218 // $response['message'] = 'Successfully Created file' . $res->id ;
219
220 // }
221 // echo wp_send_json([$response]);
222 // wp_die();
223 // }
224 public function openai_finetune_create($file_id,$ft_suffix,$ft_engines){
225 $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
226 $headers = array(
227 "Content-Type: application/json",
228 $apt_key,
229 );
230 $curl = curl_init();
231 $qcld_openai_suffix = isset($ft_suffix) ? $ft_suffix : get_option('qcld_openai_suffix');
232 $openai_engines = isset($ft_engines) ? $ft_engines : get_option('openai_engines');
233 $base_engine = explode('-',$openai_engines);
234 if( $base_engine[0] == 'gpt'){
235 $data = json_encode(array('training_file'=>$file_id,'model' => $openai_engines, 'suffix' => $qcld_openai_suffix ));
236 $url = "https://api.openai.com/v1/fine_tuning/jobs";
237 curl_setopt($curl, CURLOPT_URL, $url);
238 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
239 curl_setopt($curl, CURLOPT_POST, true);
240 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
241 curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
242 $result = json_decode(curl_exec($curl));
243 curl_close($curl);
244 }else{
245
246 $data = json_encode(array('training_file'=>$file_id,'model' => $base_engine[1], 'suffix' => $qcld_openai_suffix ));
247 $url = "https://api.openai.com/v1/fine-tunes";
248 curl_setopt($curl, CURLOPT_URL, $url);
249 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
250 curl_setopt($curl, CURLOPT_POST, true);
251 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
252 curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
253 $result = json_decode(curl_exec($curl));
254 curl_close($curl);
255 }
256 return $result;
257 }
258 public function relevant_pagelink($search_query){
259
260 $stopwords = explode( ',', get_option('qlcd_wp_chatbot_stop_words') );
261
262 $finalQueryWordsWithoutStopWords = $this->qcpd_remove_wa_stopwords( strtolower($search_query), $stopwords );
263
264 $cleanWordsWithoutPunctuationMarks = preg_replace('/[\p{P}]/u', '', $finalQueryWordsWithoutStopWords);
265
266 $q = trim($cleanWordsWithoutPunctuationMarks);
267
268 $links = [];
269
270 $post_type_array = ['post','page'];
271
272 //Proceeding with traditional search
273
274 $the_query = new WP_Query( array( 'post_status' => 'publish', 'posts_per_page' => 5, 's' => esc_attr( $q ), 'post_type' => $post_type_array ) );
275
276 if( $the_query->have_posts() ){
277
278 while( $the_query->have_posts() ){
279
280 $the_query->the_post();
281
282 $url = esc_url( get_permalink() );
283
284 $link = '<li><mark><a style="color: #000" href=' . $url . '>' . get_the_title() . '</a><mark></li>';
285
286 array_push($links, $link);
287
288 } //End of WHILE
289
290 wp_reset_postdata();
291
292 } //End of IF
293
294 $links = array_unique($links);
295
296 return $links;
297
298 } //End of function relevant_pagelink()
299 public function openai_retrive_fine_tune($keyword){
300
301 $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
302 $headers = array(
303 "Content-Type: application/json",
304 $apt_key,
305 );
306 $curl = curl_init();
307 $max_tokens = (int)get_option( 'openai_max_tokens');
308 $temp = (float)get_option( 'openai_temperature');
309 $frequency_penalty = (float)get_option( 'frequency_penalty');
310 $presence_penalty = (float)get_option( 'presence_penalty');
311 $engines = explode('-',get_option( 'openai_engines'));
312 $custom_model = get_option( 'qcld_openai_custom_model');
313 $custom_model = (explode(":",$custom_model));
314 $prompts = $this->get_prompt($keyword);
315
316 if($custom_model[1] != 'gpt-3.5-turbo-0613'){
317 $data = json_encode(array(
318 'prompt'=> $prompts,
319 'model'=> get_option( 'qcld_openai_custom_model'),
320 "max_tokens" => $max_tokens,
321 "temperature" => $temp,
322 "top_p" => 1,
323 "presence_penalty" => $frequency_penalty,
324 "frequency_penalty"=> $presence_penalty,
325 "best_of"=> 1,
326 "stop"=> ["\n###\n","###"]
327 ));
328 $url = "https://api.openai.com/v1/completions";
329
330 $ch = curl_init();
331
332 curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/completions');
333 // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
334 // curl_setopt($ch, CURLOPT_POST, 1);
335 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
336 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
337 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
338 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
339
340 $result = (curl_exec($ch));
341 $result = str_replace("#","",$result );
342
343 return $result;
344 if (curl_errno($ch)) {
345 // phpcs:ignore
346 echo esc_html('Error: ' . curl_error($ch));
347 }
348 curl_close($ch);
349 }else{
350 $data = json_encode(array(
351 'model'=> get_option( 'qcld_openai_custom_model'),
352 "messages"=> [
353
354 [
355 "role"=> "user",
356 "content"=>$keyword
357 ]
358
359 ],
360
361 ));
362 $ch = curl_init();
363
364 curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
365 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
366 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
367 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
368 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
369
370 $results = (curl_exec($ch));
371 $results = str_replace("#","",$result );
372 $result = (json_decode($results)->choices[0]->message->content);
373 return $result;
374
375
376 }
377
378 }
379 public function response_form_file($keyword){
380 $max_tokens = (int)get_option( 'openai_max_tokens');
381 $temp = (float)get_option( 'openai_temperature');
382 $frequency_penalty = (float)get_option( 'frequency_penalty');
383 $presence_penalty = (float)get_option( 'presence_penalty');
384 $engines = explode('-',get_option( 'openai_engines'));
385 if($engines[0] != 'gpt'){
386 // $prompts = $this->get_prompt($keyword);
387 }
388
389 $request_body = [
390 "prompt" => $keyword,
391 "model" => get_option( 'qcld_openai_custom_model'),
392 "max_tokens" => $max_tokens,
393 "temperature" => 0,
394 "top_p" => 1,
395 "stop" => [],
396 "presence_penalty" => 0,
397 "frequency_penalty"=> 0,
398 "best_of"=> 1,
399 ];
400 $postFields = json_encode($request_body);
401 $OpenAI = new qcld_wp_OpenAI();
402 $result = $OpenAI->get_response($postFields);
403
404 return $result;
405 }
406 public function get_prompt($keyword){
407 $openai_include_keyword = get_option( 'openai_include_keyword');
408 $openai_exclude_keyword = get_option( 'openai_exclude_keyword');
409 $qcld_openai_prompt = get_option('qcld_openai_prompt',true);
410
411 }
412 public function include_exclude_prompt($keyword){
413 $openai_include_keyword = strtolower(get_option('openai_include_keyword'));
414 $openai_exclude_keyword = strtolower(get_option('openai_exclude_keyword'));
415
416 if((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') == '')){
417 $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;
418 return $prompts;
419 }else if((get_option('openai_include_keyword') == '') || (get_option('openai_exclude_keyword') != '')){
420
421 $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';
422 return $prompts;
423 }else if((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')){
424 $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;
425 return $prompts;
426 }
427 }
428 public function qcld_include_keyword_exist( $keyword ){
429 $keyword = isset($keyword) ? $keyword : '';
430 $openai_include_keywords = strtolower(get_option('openai_include_keyword'));
431 if(!empty($keyword)){
432 $openai_include_keyword = ( isset( $openai_include_keywords ) ? $openai_include_keywords : '');
433
434 if( !empty($openai_include_keyword)){
435 $include_items = explode(',', $openai_include_keyword);
436 if(!empty($include_items)){
437 foreach($include_items as $k => $item){
438 if((strpos($keyword,trim($item)) !== false) && !empty($item)){
439 return true;
440 }
441 }
442 }
443 return false;
444 }
445 }
446
447 return false;
448
449 }
450 public function openai_response_callback() {
451 // $nonce = sanitize_text_field($_POST['nonce']);
452 // if (! wp_verify_nonce($nonce,'qcsecretbotnonceval123qc')) {
453 // wp_send_json(array('success' => false, 'msg' => esc_html__('Failed in Security check', 'chatbot')));
454 // wp_die();
455
456 // }else{
457 if (get_option('is_rate_limiting_enabled') == '1') {
458 do_action('rate_limit_checker');
459 }
460 $response['status'] = 'success';
461 $response['message'] ='A preset message';
462 $OpenAI = new qcld_wp_OpenAI();
463 $gptkeyword = [];
464 $keyword = sanitize_text_field($_POST['keyword']);
465 $relevant_pagelink = $this->relevant_pagelink($keyword);
466
467 $relevant_pagelink = array_slice($relevant_pagelink, 0, 5, true);
468 if( (get_option('page_suggestion_enabled') == '1') && count($relevant_pagelink) > 0 ){
469
470 $relevant_post_link = get_option('qlcd_wp_chatbot_relevant_post_link_openai');
471
472 if(is_array($relevant_post_link )){
473
474 $relevant_pagelinks = '<br><br><p><em>'. implode('', $relevant_post_link) .'</em></p><ul style="list-style: disc;padding-left: 10px;">'. implode(" ", $relevant_pagelink). '</ul>';
475 }else{
476 $relevant_pagelinks = '<br><br><p><em>'. $relevant_post_link .'</em></p><ul style="list-style: disc;padding-left: 10px;">'. implode(" ", $relevant_pagelink) .'</ul>';
477 }
478 }else{
479 $relevant_pagelinks = '';
480 }
481 if(get_option( 'is_asst_enabled') != 1){
482 $response_files = $this->openai_retrive_fine_tune($keyword);
483 $response_file = json_decode($response_files, true);
484 $gptkeywords = [];
485 if((empty($response_file['choices'][0]["text"])) && empty($response_file['choices'][0]["message"]['content'])){
486 array_push( $gptkeyword, array(
487 "role" => "system",
488 "content" => get_option('qcld_openai_system_content')
489 ));
490 array_push($gptkeyword, array(
491 "role" => "user",
492 "content" => $keyword
493 ));
494 if(((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')) && (get_option('qcld_openai_relevant_enabled') == '1') ){
495 $prompts = $this->include_exclude_prompt($keyword);
496
497 $gptkeyword = [];
498 array_push($gptkeyword, array(
499 "role" => "user",
500 "content" => $prompts,
501 ));
502 }else if(((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')) && (get_option('qcld_openai_relevant_enabled') == '0')){
503 if($this->qcld_include_keyword_exist($keyword) == false){
504
505 $response['message'] = 'Sorry, No result found!';
506 echo wp_json_encode($response);
507 wp_die();
508 }else{
509 array_push($gptkeyword, array(
510 "role" => "user",
511 "content" => $keyword
512 ));
513 }
514
515 }
516 $res = $OpenAI->gptcomplete(
517 $gptkeyword
518 );
519 $mess = json_decode($res);
520
521 $Qcld_Parsedown = new Qcld_Parsedown();
522 $msg = $mess->output[0]->content[0]->text;
523 $msg = $Qcld_Parsedown->text($msg);
524 $response['message'] = $msg ;
525 if(($response['message'] == 'DUH.') || ($response['message'] == 'DUH')){
526 $response['message'] = 'Sorry, No result found!';
527 }else{
528 $Qcld_Parsedown = new Qcld_Parsedown();
529 $msg = $mess->output[0]->content[0]->text;
530 $msg = $Qcld_Parsedown->text($msg);
531 $response['message'] = $msg . $relevant_pagelinks;
532 }
533 }else if(!empty($response_file['choices'][0]["message"]['content'])){
534 $result = $response_file['choices'][0]["message"]['content'];
535 $Qcld_Parsedown = new Qcld_Parsedown();
536 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$result);
537 $response['message'] = $msg . $relevant_pagelinks;
538 }else{
539 $result = $response_file['choices'][0]["text"];
540 $message = explode(">",$result);
541 if(empty($message)){
542 $message = $result;
543 }elseif(empty($message[1])){
544 $message = $message[0];
545 }else{
546 $message = $message[1];
547 }
548 $Qcld_Parsedown = new Qcld_Parsedown();
549 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$message);
550 $message = $Qcld_Parsedown->text($msg);
551 if(get_option('conversation_continuity') == 1){
552 $lasfivecookie = $_COOKIE["last_five_prompt"] . $message . '###';
553 setcookie('last_five_prompt', $lasfivecookie, time() + (60000), "/");
554 $response['cookie'] = $lasfivecookie;
555 }
556 $response['message'] = $message . $relevant_pagelinks;
557 }
558 }else{
559 $url = 'https://api.openai.com/v1/threads';
560 $api_key = get_option('open_ai_api_key');
561 $engines = get_option( 'openai_engines');
562
563 $header = [
564 'Content-Type: application/json',
565 'OpenAI-Beta: assistants=v1',
566 'Authorization: Bearer ' . $api_key
567 ];
568 // $threads_id = '';
569 $threads_id_COOKIE = $_COOKIE["qcld_threads_id"];
570 $threads_id = $threads_id_COOKIE;
571 if(($threads_id == '')){
572
573 $ch = curl_init();
574 curl_setopt($ch, CURLOPT_URL, $url);
575 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
576 curl_setopt($ch, CURLOPT_POST, 1);
577 // curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));
578 curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
579 $threads = curl_exec($ch);
580 $threads_id = json_decode($threads)->id;
581 setcookie('qcld_threads_id',$threads_id , time() + (60000), "/");
582 if (curl_errno($ch)) {
583 // phpcs:ignore
584 echo 'Error: ' . curl_error($ch);
585 }
586 curl_close($ch);
587 }
588
589 $msg = $this->add_on_thrrads($threads_id,$keyword);
590 $Qcld_Parsedown = new Qcld_Parsedown();
591 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$msg);
592 $message = $Qcld_Parsedown->text($msg);
593 $response['message'] = $message . $relevant_pagelinks;
594
595 }
596 do_action('qcld_openai_user_rate_cal', 1);
597 echo wp_json_encode($response);
598 wp_die();
599 //}
600 }
601 public function openai_settings_option_callback() {
602 $nonce = sanitize_text_field($_POST['nonce']);
603
604 if (! wp_verify_nonce($nonce,'wp_chatbot')) {
605 wp_send_json(array('success' => false, 'msg' => esc_html__('Failed in Security check', 'chatbot')));
606 wp_die();
607
608 }else{
609
610 $api_key = sanitize_text_field($_POST['api_key']);
611 $openai_engines = sanitize_text_field($_POST['openai_engines']);
612 $qcld_openai_prompt = sanitize_text_field($_POST['qcld_openai_prompt']);
613 $max_tokens = sanitize_text_field($_POST['max_tokens']);
614 $qcld_openai_suffix = (!empty($_POST['qcld_openai_suffix'])) ? sanitize_text_field($_POST['qcld_openai_suffix']) : '';
615 $qcld_openai_custom_model = sanitize_text_field($_POST['qcld_openai_custom_model']);
616 $frequency_penalty = sanitize_text_field($_POST['frequency_penalty']);
617 $presence_penalty = sanitize_text_field($_POST['presence_penalty']);
618 $temperature = sanitize_text_field($_POST['temperature']);
619 $ai_enabled = sanitize_text_field($_POST['ai_enabled']);
620 $suggestion_enabled = sanitize_text_field($_POST['is_page_suggestion_enabled']);
621 $is_relevant_enabled = sanitize_text_field($_POST['is_relevant_enabled']);
622 $file_id = (!empty($_POST['file_id'])) ? sanitize_text_field($_POST['file_id']) : '';
623 $qcld_openai_prompt_custom = sanitize_text_field($_POST['qcld_openai_prompt_custom']);
624 $conversation_continuity = sanitize_text_field($_POST['conversation_continuity']);
625 $qcld_openai_system_content = sanitize_text_field($_POST['qcld_openai_system_content']);
626 /* Customized by Kadir on 05-12-2023 : To set empty value for API field */
627
628 $disable_ss = sanitize_text_field($_POST['disable_ss']);
629
630 if($api_key != ''){
631 update_option( 'open_ai_api_key', $api_key );
632 }
633 else{
634 delete_option( 'open_ai_api_key');
635 }
636
637 /* Ends: Customized by Kadir on 05-12-2023 : To set empty value for API field */
638
639 if($openai_engines != ''){
640 update_option( 'openai_engines', $openai_engines );
641 }
642 if($conversation_continuity != ''){
643 update_option( 'conversation_continuity', $conversation_continuity );
644 }
645 update_option( 'openai_max_tokens', $max_tokens );
646
647 if($qcld_openai_suffix != ''){
648 update_option('qcld_openai_suffix', $qcld_openai_suffix);
649 }
650 if($frequency_penalty != ''){
651 update_option( 'frequency_penalty', $frequency_penalty );
652 }
653 if($presence_penalty != ''){
654 update_option( 'presence_penalty', $presence_penalty );
655 }
656 if($temperature != ''){
657 update_option( 'openai_temperature', $temperature );
658 }
659 if($qcld_openai_prompt_custom != ''){
660 update_option('qcld_openai_prompt_custom', $qcld_openai_prompt_custom );
661 }
662 update_option('qcld_openai_custom_model',$qcld_openai_custom_model);
663 update_option('qcld_openai_system_content', stripslashes( $qcld_openai_system_content));
664 update_option('ai_enabled',$ai_enabled);
665 update_option('qcld_openai_relevant_enabled',$is_relevant_enabled);
666 update_option('page_suggestion_enabled',$suggestion_enabled);
667 if($file_id != ''){
668 update_option('file_id',$file_id);
669 }
670 $openai_include_keyword = sanitize_text_field($_POST['openai_include_keyword']);
671 update_option('openai_include_keyword',$openai_include_keyword);
672 $openai_exclude_keyword = sanitize_text_field($_POST['openai_exclude_keyword']);
673 update_option('openai_exclude_keyword',$openai_exclude_keyword);
674
675
676 /* Customized by Kadir on 05-12-2023 : To Disable Site Search*/
677 //Disable Site Search
678 if( $disable_ss == 1 ){
679 update_option('disable_wp_chatbot_site_search',1);
680 }
681 /* Ends: Customized by Kadir on 05-12-2023 : To Disable Site Search*/
682
683
684
685 }
686 if($qcld_openai_prompt != ''){
687 update_option('qcld_openai_prompt', $qcld_openai_prompt);
688 }
689 $tem = get_option( 'openai_temperature', $temperature );
690
691 echo wp_json_encode($ai_enabled);wp_die();
692
693 }
694 public function qcpd_remove_wa_stopwords($query, $stopwords){
695
696 return preg_replace('/\b('.implode('|',$stopwords).')\b/','',$query);
697
698 }
699 public function openai_troubleshooting(){
700 $nonce = sanitize_text_field($_POST['nonce']);
701 $OpenAI = new qcld_wp_OpenAI();
702 if (! wp_verify_nonce($nonce,'wp_chatbot')) {
703 wp_send_json(array('success' => false, 'msg' => esc_html__('Failed in Security check', 'chatbot')));
704 wp_die();
705
706 }else{
707 $gptkeyword = [];
708 array_push($gptkeyword, array(
709 "role" => "user",
710 "content" => "Is our request comes from openAI ?"
711 ));
712 $res = $OpenAI->gptcomplete(
713 $gptkeyword
714 );
715 if(empty(json_decode($res)->error)){
716 $mess = json_decode($res);
717 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$mess->choices[0]->message->content);
718 wp_send_json(array('success' => true,'title' => esc_html__('success', 'chatbot'),'icon'=>esc_html__('alert-success', 'chatbot'),'msg' => wp_kses_post($msg)));
719 }else{
720 // If there's an error, the 'success' flag should be false.
721 wp_send_json(array('success' => false,'title' => esc_html__('Error', 'chatbot'),'icon'=>esc_html__('error', 'chatbot'), 'msg' => esc_html(json_decode($res)->error->message)));
722 }
723 }
724 }
725
726
727 }
728
729 /**
730 * @return qcld_wpopenai_addon
731 */
732 if(!function_exists('qcld_wpopenai_addons')){
733 function qcld_openais() {
734 $qcld_wpopenai_addon = new qcld_wpopenai_addons();
735 return $qcld_wpopenai_addon->instance();
736
737 }
738 }
739
740 //fire off the plugin
741 qcld_openais();
742
743 }