| 1 |
<?php |
| 2 |
include_once(ABSPATH . 'wp-includes/pluggable.php'); |
| 3 |
if(!class_exists('qcld_wp_OpenAI')){ |
| 4 |
class qcld_wp_OpenAI{ |
| 5 |
public $baseURL = "https://api.openai.com/v1/"; |
| 6 |
private $defaultEngine = "davinci"; |
| 7 |
public function setDefaultEngine($defaultEngine){ |
| 8 |
$this->defaultEngine = $defaultEngine; |
| 9 |
} |
| 10 |
|
| 11 |
public function get_response($postFields){ |
| 12 |
$url = "https://api.openai.com/v1/completions"; |
| 13 |
$apt_key = "Authorization: Bearer ". get_option('open_ai_api_key'); |
| 14 |
|
| 15 |
$curl = curl_init($url); |
| 16 |
curl_setopt($curl, CURLOPT_URL, $url); |
| 17 |
curl_setopt($curl, CURLOPT_POST, true); |
| 18 |
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); |
| 19 |
|
| 20 |
$headers = array( |
| 21 |
"Content-Type: application/json", |
| 22 |
$apt_key , |
| 23 |
); |
| 24 |
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); |
| 25 |
|
| 26 |
|
| 27 |
curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields); |
| 28 |
|
| 29 |
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); |
| 30 |
$response = curl_exec($curl); |
| 31 |
curl_close($curl); |
| 32 |
|
| 33 |
|
| 34 |
return json_decode($response); |
| 35 |
} |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
public function complete( $prompt) { |
| 40 |
$max_tokens = (int)get_option( 'openai_max_tokens'); |
| 41 |
$temp = (float)get_option( 'openai_temperature'); |
| 42 |
$frequency_penalty = (float)get_option( 'frequency_penalty'); |
| 43 |
$presence_penalty = (float)get_option( 'presence_penalty'); |
| 44 |
$request_body = [ |
| 45 |
"prompt" => $prompt, |
| 46 |
"model" => get_option( 'openai_engines'), |
| 47 |
"max_tokens" => $max_tokens, |
| 48 |
"temperature" => $temp, |
| 49 |
"top_p" => 1, |
| 50 |
"presence_penalty" => $presence_penalty, |
| 51 |
"frequency_penalty"=> $frequency_penalty, |
| 52 |
"best_of"=> 1, |
| 53 |
"stream" => false, |
| 54 |
]; |
| 55 |
$postFields = json_encode($request_body); |
| 56 |
|
| 57 |
|
| 58 |
$result = self::get_response($postFields); |
| 59 |
// var_dump(json_encode($result));wp_die(); |
| 60 |
return json_encode($result); |
| 61 |
// return $returnResult ? ($json ? json_encode($result) : $result) : $this->_removeUnfinishedSentence($prompt . ($result?->choices[0]?->text ?? "")); |
| 62 |
|
| 63 |
} |
| 64 |
} |
| 65 |
} |