modules
3 years ago
admin.php
3 years ago
ai.php
3 years ago
answer.php
3 years ago
core.php
3 years ago
init.php
3 years ago
openai.php
3 years ago
query.php
3 years ago
queryimage.php
3 years ago
querytext.php
3 years ago
rest.php
3 years ago
ui.php
3 years ago
openai.php
276 lines
| 1 | <?php |
| 2 | |
| 3 | class Meow_MWAI_OpenAI |
| 4 | { |
| 5 | private $core = null; |
| 6 | private $apiKey = null; |
| 7 | |
| 8 | public function __construct($core) |
| 9 | { |
| 10 | $this->core = $core; |
| 11 | $this->apiKey = $this->core->get_option('openai_apikey'); |
| 12 | } |
| 13 | |
| 14 | public function listFiles() |
| 15 | { |
| 16 | return $this->run('GET', '/files'); |
| 17 | } |
| 18 | |
| 19 | function getSuffixForModel($model) |
| 20 | { |
| 21 | preg_match("/:([a-zA-Z\-]{1,40})-([0-9]{4})-([0-9]{2})-([0-9]{2})/", $model, $matches); |
| 22 | if (count($matches) > 0) { |
| 23 | return $matches[1]; |
| 24 | } |
| 25 | return 'N/A'; |
| 26 | } |
| 27 | |
| 28 | function getBaseModel($model) |
| 29 | { |
| 30 | preg_match("/:([a-zA-Z\-]{1,40})-([0-9]{4})-([0-9]{2})-([0-9]{2})/", $model, $matches); |
| 31 | if (count($matches) > 0) { |
| 32 | return $matches[1]; |
| 33 | } |
| 34 | return 'N/A'; |
| 35 | } |
| 36 | |
| 37 | public function listFineTunes( $clean = false ) |
| 38 | { |
| 39 | $finetunes = $this->run('GET', '/fine-tunes'); |
| 40 | |
| 41 | if ( $clean ) { |
| 42 | $deleted = []; |
| 43 | $finetunes['data'] = array_filter( $finetunes['data'], function ( $finetune ) use ( &$deleted ) { |
| 44 | $name = $finetune['fine_tuned_model']; |
| 45 | $exist = true; |
| 46 | try { |
| 47 | $finetune = $this->getModel( $name ); |
| 48 | } |
| 49 | catch ( Exception $e ) { |
| 50 | $exist = false; |
| 51 | $deleted[] = $name; |
| 52 | } |
| 53 | return $exist; |
| 54 | }); |
| 55 | $this->core->update_option( 'openai_finetunes_deleted', $deleted ); |
| 56 | } |
| 57 | |
| 58 | $finetunes['data'] = array_map( function ( $finetune ) { |
| 59 | $finetune['suffix'] = $this->getSuffixForModel( $finetune['fine_tuned_model'] ); |
| 60 | return $finetune; |
| 61 | }, $finetunes['data']); |
| 62 | |
| 63 | // Get option openai_finetunes_deleted |
| 64 | $deleted_finetunes = $this->core->get_option('openai_finetunes_deleted'); |
| 65 | |
| 66 | // Remove all deleted finetunes from the list, make a new array, without using array_filter |
| 67 | $finetunes['data'] = array_values(array_filter($finetunes['data'], function ($finetune) use ($deleted_finetunes) { |
| 68 | return !in_array($finetune['fine_tuned_model'], $deleted_finetunes); |
| 69 | })); |
| 70 | |
| 71 | $finetunes_option = $this->core->get_option('openai_finetunes'); |
| 72 | $fresh_finetunes_options = array_map(function ($finetune) use ($finetunes_option) { |
| 73 | $entry = []; |
| 74 | $model = $finetune['fine_tuned_model']; |
| 75 | $entry['suffix'] = $finetune['suffix']; |
| 76 | $entry['model'] = $model; |
| 77 | $entry['enabled'] = true; |
| 78 | for ($i = 0; $i < count($finetunes_option); $i++) { |
| 79 | if ($finetunes_option[$i]['model'] === $model) { |
| 80 | $entry['enabled'] = $finetunes_option[$i]['enabled']; |
| 81 | break; |
| 82 | } |
| 83 | } |
| 84 | return $entry; |
| 85 | }, $finetunes['data']); |
| 86 | $this->core->update_option('openai_finetunes', $fresh_finetunes_options); |
| 87 | return $finetunes; |
| 88 | } |
| 89 | |
| 90 | public function uploadFile( $filename, $data ) |
| 91 | { |
| 92 | $result = $this->run('POST', '/files', null, ['data' => $data, 'filename' => $filename]); |
| 93 | return $result; |
| 94 | } |
| 95 | |
| 96 | public function deleteFile( $fileId ) |
| 97 | { |
| 98 | return $this->run('DELETE', '/files/' . $fileId); |
| 99 | } |
| 100 | |
| 101 | public function getModel( $modelId ) |
| 102 | { |
| 103 | return $this->run('GET', '/models/' . $modelId); |
| 104 | } |
| 105 | |
| 106 | public function deleteFineTune( $modelId ) |
| 107 | { |
| 108 | return $this->run('DELETE', '/models/' . $modelId); |
| 109 | } |
| 110 | |
| 111 | public function downloadFile( $fileId ) |
| 112 | { |
| 113 | return $this->run('GET', '/files/' . $fileId . '/content', null, null, false); |
| 114 | } |
| 115 | |
| 116 | public function fineTuneFile($fileId, $model, $suffix) |
| 117 | { |
| 118 | $result = $this->run('POST', '/fine-tunes', [ |
| 119 | 'training_file' => $fileId, |
| 120 | 'model' => $model, |
| 121 | 'suffix' => $suffix |
| 122 | ]); |
| 123 | return $result; |
| 124 | } |
| 125 | |
| 126 | public function create_body_for_file($file, $boundary) |
| 127 | { |
| 128 | $fields = array( |
| 129 | 'purpose' => 'fine-tune', |
| 130 | 'file' => $file['filename'] |
| 131 | ); |
| 132 | |
| 133 | $body = ''; |
| 134 | foreach ($fields as $name => $value) { |
| 135 | $body .= "--$boundary\r\n"; |
| 136 | $body .= "Content-Disposition: form-data; name=\"$name\""; |
| 137 | if ($name == 'file') { |
| 138 | $body .= "; filename=\"{$value}\"\r\n"; |
| 139 | $body .= "Content-Type: application/json\r\n\r\n"; |
| 140 | $body .= $file['data'] . "\r\n"; |
| 141 | } else { |
| 142 | $body .= "\r\n\r\n$value\r\n"; |
| 143 | } |
| 144 | } |
| 145 | $body .= "--$boundary--\r\n"; |
| 146 | return $body; |
| 147 | } |
| 148 | |
| 149 | public function run($method, $url, $query = null, $file = null, $json = true) |
| 150 | { |
| 151 | $apiKey = $this->apiKey; |
| 152 | $headers = "Content-Type: application/json\r\n" . "Authorization: Bearer " . $apiKey . "\r\n"; |
| 153 | $body = $query ? json_encode($query) : null; |
| 154 | if (!empty($file)) { |
| 155 | $boundary = wp_generate_password(24, false); |
| 156 | $headers = [ |
| 157 | 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, |
| 158 | 'Authorization' => 'Bearer ' . $this->apiKey, |
| 159 | ]; |
| 160 | $body = $this->create_body_for_file($file, $boundary); |
| 161 | } |
| 162 | |
| 163 | $url = 'https://api.openai.com/v1' . $url; |
| 164 | $options = [ |
| 165 | "headers" => $headers, |
| 166 | "method" => $method, |
| 167 | "timeout" => 120, |
| 168 | "body" => $body, |
| 169 | "sslverify" => false |
| 170 | ]; |
| 171 | |
| 172 | try { |
| 173 | $response = wp_remote_request($url, $options); |
| 174 | if (is_wp_error($response)) { |
| 175 | throw new Exception($response->get_error_message()); |
| 176 | } |
| 177 | $response = wp_remote_retrieve_body($response); |
| 178 | $data = $json ? json_decode($response, true) : $response; |
| 179 | |
| 180 | // Error handling |
| 181 | if (isset($data['error'])) { |
| 182 | $message = $data['error']['message']; |
| 183 | // If the message contains "Incorrect API key provided: THE_KEY.", replace the key by "----". |
| 184 | if (preg_match('/API key provided(: .*)\./', $message, $matches)) { |
| 185 | $message = str_replace($matches[1], '', $message); |
| 186 | } |
| 187 | throw new Exception($message); |
| 188 | } |
| 189 | |
| 190 | return $data; |
| 191 | } |
| 192 | catch (Exception $e) { |
| 193 | error_log($e->getMessage()); |
| 194 | throw new Exception('Error while calling OpenAI: ' . $e->getMessage()); |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | private function calculatePrice( $model, $units, $option = null ) |
| 199 | { |
| 200 | foreach ( MWAI_OPENAI_PRICING as $price ) { |
| 201 | if ( $price['model'] == $model ) { |
| 202 | if ( $price['type'] == 'image' ) { |
| 203 | if ( !$option ) { |
| 204 | error_log( "AI Engine: Image models require an option." ); |
| 205 | return null; |
| 206 | } |
| 207 | else { |
| 208 | foreach ( $price['options'] as $imageType ) { |
| 209 | if ( $imageType['option'] == $option ) { |
| 210 | return $imageType['price'] * $units; |
| 211 | } |
| 212 | } |
| 213 | } |
| 214 | } |
| 215 | else { |
| 216 | return $price['price'] * $price['unit'] * $units; |
| 217 | } |
| 218 | } |
| 219 | } |
| 220 | error_log( "AI Engine: Invalid model ($model)." ); |
| 221 | return null; |
| 222 | } |
| 223 | |
| 224 | public function getPrice( Meow_MWAI_Query $query, Meow_MWAI_Answer $answer ) |
| 225 | { |
| 226 | $model = $query->model; |
| 227 | $modelBase = null; |
| 228 | $units = 0; |
| 229 | $option = null; |
| 230 | if ( is_a( $query, 'Meow_MWAI_QueryText' ) ) { |
| 231 | // Finetuned models |
| 232 | if ( preg_match('/^([a-zA-Z]{0,32}):/', $model, $matches ) ) { |
| 233 | $modelBase = "fn-" . $matches[1]; |
| 234 | } |
| 235 | // Standard models |
| 236 | else if ( preg_match('/^text-(\w+)-\d+/', $model, $matches ) ) { |
| 237 | $modelBase = $matches[1]; |
| 238 | } |
| 239 | if ( empty( $modelBase ) ) { |
| 240 | error_log("AI Engine: Cannot find the base model for $model."); |
| 241 | return null; |
| 242 | } |
| 243 | $units = $answer->getTotalTokens(); |
| 244 | } |
| 245 | else if ( is_a( $query, 'Meow_MWAI_QueryImage' ) ) { |
| 246 | $modelBase = 'dall-e'; |
| 247 | $units = $query->maxResults; |
| 248 | $option = "1024x1024"; |
| 249 | } |
| 250 | return $this->calculatePrice( $modelBase, $units, $option ); |
| 251 | } |
| 252 | |
| 253 | public function getIncidents() { |
| 254 | $url = 'https://status.openai.com/history.rss'; |
| 255 | $response = wp_remote_get( $url ); |
| 256 | if ( is_wp_error( $response ) ) { |
| 257 | throw new Exception( $response->get_error_message() ); |
| 258 | } |
| 259 | $response = wp_remote_retrieve_body( $response ); |
| 260 | $xml = simplexml_load_string( $response ); |
| 261 | $incidents = array(); |
| 262 | $oneWeekAgo = time() - 7 * 24 * 60 * 60; |
| 263 | foreach ( $xml->channel->item as $item ) { |
| 264 | $date = strtotime( $item->pubDate ); |
| 265 | if ( $date > $oneWeekAgo ) { |
| 266 | $incidents[] = array( |
| 267 | 'title' => (string) $item->title, |
| 268 | 'description' => (string) $item->description, |
| 269 | 'date' => $date |
| 270 | ); |
| 271 | } |
| 272 | } |
| 273 | return $incidents; |
| 274 | } |
| 275 | } |
| 276 |