modules
3 years ago
admin.php
3 years ago
ai.php
3 years ago
answer.php
3 years ago
api.php
3 years ago
core.php
3 years ago
init.php
3 years ago
openai.php
3 years ago
query.php
3 years ago
queryembed.php
3 years ago
queryimage.php
3 years ago
querytext.php
3 years ago
querytranscribe.php
3 years ago
rest.php
3 years ago
ui.php
3 years ago
ai.php
265 lines
| 1 | <?php |
| 2 | |
| 3 | class Meow_MWAI_AI { |
| 4 | private $core = null; |
| 5 | private $localApiKey = null; |
| 6 | private $localService = null; |
| 7 | private $localAzureEndpoint = null; |
| 8 | private $localAzureApiKey = null; |
| 9 | private $localAzureDeployment = null; |
| 10 | |
| 11 | public function __construct( $core ) { |
| 12 | $this->core = $core; |
| 13 | $this->localService = $this->core->get_option( 'openai_service' ); |
| 14 | $this->localApiKey = $this->core->get_option( 'openai_apikey' ); |
| 15 | $this->localAzureEndpoint = $this->core->get_option( 'openai_azure_endpoint' ); |
| 16 | $this->localAzureApiKey = $this->core->get_option( 'openai_azure_apikey' ); |
| 17 | $this->localAzureDeployment = $this->core->get_option( 'openai_azure_deployment' ); |
| 18 | } |
| 19 | |
| 20 | public function applyQueryParameters( $query ) { |
| 21 | if ( empty( $query->apiKey ) ) { |
| 22 | $query->apiKey = $this->localApiKey; |
| 23 | } |
| 24 | if ( empty( $query->service ) ) { |
| 25 | $query->service = $this->localService; |
| 26 | } |
| 27 | if ( $query->service === 'azure' ) { |
| 28 | if ( empty( $query->azureEndpoint ) ) { |
| 29 | $query->azureEndpoint = $this->localAzureEndpoint; |
| 30 | } |
| 31 | if ( empty( $query->azureApiKey ) ) { |
| 32 | $query->azureApiKey = $this->localAzureApiKey; |
| 33 | } |
| 34 | if ( empty( $query->azureDeployment ) ) { |
| 35 | $query->azureDeployment = $this->localAzureDeployment; |
| 36 | } |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | public function runTranscribe( $query ) { |
| 41 | $this->applyQueryParameters( $query ); |
| 42 | $openai = new Meow_MWAI_OpenAI( $this->core ); |
| 43 | $fields = array( |
| 44 | 'prompt' => $query->prompt, |
| 45 | 'model' => $query->model, |
| 46 | 'response_format' => 'text', |
| 47 | 'file' => basename( $query->url ), |
| 48 | 'data' => file_get_contents( $query->url ) |
| 49 | ); |
| 50 | $modeEndpoint = $query->mode === 'translation' ? 'translations' : 'transcriptions'; |
| 51 | $data = $openai->run( 'POST', '/audio/' . $modeEndpoint, null, $fields, false ); |
| 52 | if ( empty( $data ) ) { |
| 53 | throw new Exception( 'Invalid data for transcription.' ); |
| 54 | } |
| 55 | //$usage = $data['usage']; |
| 56 | //$this->core->record_tokens_usage( $query->model, $usage['prompt_tokens'] ); |
| 57 | $answer = new Meow_MWAI_Answer( $query ); |
| 58 | //$answer->setUsage( $usage ); |
| 59 | $answer->setChoices( $data ); |
| 60 | return $answer; |
| 61 | } |
| 62 | |
| 63 | public function runEmbedding( $query ) { |
| 64 | $this->applyQueryParameters( $query ); |
| 65 | $openai = new Meow_MWAI_OpenAI( $this->core ); |
| 66 | $body = array( 'input' => $query->prompt, 'model' => $query->model ); |
| 67 | $data = $openai->run( 'POST', '/embeddings', $body ); |
| 68 | if ( empty( $data ) || !isset( $data['data'] ) ) { |
| 69 | throw new Exception( 'Invalid data for embedding.' ); |
| 70 | } |
| 71 | $usage = $data['usage']; |
| 72 | $this->core->record_tokens_usage( $query->model, $usage['prompt_tokens'] ); |
| 73 | $answer = new Meow_MWAI_Answer( $query ); |
| 74 | $answer->setUsage( $usage ); |
| 75 | $answer->setChoices( $data['data'] ); |
| 76 | return $answer; |
| 77 | } |
| 78 | |
| 79 | public function runCompletion( $query ) { |
| 80 | $this->applyQueryParameters( $query ); |
| 81 | $url = ""; |
| 82 | $headers = array( |
| 83 | 'Content-Type' => 'application/json', |
| 84 | 'Authorization' => 'Bearer ' . $query->apiKey, |
| 85 | ); |
| 86 | $body = array( |
| 87 | "model" => $query->model, |
| 88 | "stop" => $query->stop, |
| 89 | "n" => $query->maxResults, |
| 90 | "max_tokens" => $query->maxTokens, |
| 91 | "temperature" => $query->temperature, |
| 92 | ); |
| 93 | |
| 94 | if ( $query->mode === 'chat' ) { |
| 95 | $url = 'https://api.openai.com/v1/chat/completions'; |
| 96 | $body['messages'] = $query->messages; |
| 97 | |
| 98 | // TODO: Let's follow closely the changes at Azure. |
| 99 | // Seems we need to specify an API version, otherwise it breaks. |
| 100 | if ( $query->service === 'azure' ) { |
| 101 | $url = trailingslashit( $query->azureEndpoint ) . 'openai/deployments/' . |
| 102 | $query->azureDeployment . '/chat/completions?api-version=2023-03-15-preview'; |
| 103 | $headers = array( |
| 104 | 'Content-Type' => 'application/json', |
| 105 | 'api-key' => $query->azureApiKey, |
| 106 | ); |
| 107 | } |
| 108 | } |
| 109 | else if ( $query->mode === 'completion' ) { |
| 110 | $url = 'https://api.openai.com/v1/completions'; |
| 111 | $body['prompt'] = $query->prompt; |
| 112 | } |
| 113 | else { |
| 114 | throw new Exception( 'Unknown mode for query: ' . $query->mode ); |
| 115 | } |
| 116 | |
| 117 | $options = array( |
| 118 | "headers" => $headers, |
| 119 | "method" => "POST", |
| 120 | "timeout" => 120, |
| 121 | "body" => json_encode( $body ), |
| 122 | "sslverify" => false |
| 123 | ); |
| 124 | |
| 125 | try { |
| 126 | $response = wp_remote_get( $url, $options ); |
| 127 | if ( is_wp_error( $response ) ) { |
| 128 | throw new Exception( $response->get_error_message() ); |
| 129 | } |
| 130 | $response = wp_remote_retrieve_body( $response ); |
| 131 | $data = json_decode( $response, true ); |
| 132 | |
| 133 | // Error handling |
| 134 | if ( isset( $data['error'] ) ) { |
| 135 | $message = $data['error']['message']; |
| 136 | // If the message contains "Incorrect API key provided: THE_KEY.", replace the key by "----". |
| 137 | if ( preg_match( '/API key provided(: .*)\./', $message, $matches ) ) { |
| 138 | $message = str_replace( $matches[1], '', $message ); |
| 139 | } |
| 140 | throw new Exception( $message ); |
| 141 | } |
| 142 | if ( !$data['model'] ) { |
| 143 | error_log( print_r( $data, 1 ) ); |
| 144 | throw new Exception( "Got an unexpected response from OpenAI. Check your PHP Error Logs." ); |
| 145 | } |
| 146 | $answer = new Meow_MWAI_Answer( $query ); |
| 147 | try { |
| 148 | $usage = $this->core->record_tokens_usage( |
| 149 | $data['model'], |
| 150 | $data['usage']['prompt_tokens'], |
| 151 | $data['usage']['completion_tokens'] |
| 152 | ); |
| 153 | } |
| 154 | catch ( Exception $e ) { |
| 155 | error_log( $e->getMessage() ); |
| 156 | } |
| 157 | $answer->setUsage( $usage ); |
| 158 | $answer->setChoices( $data['choices'] ); |
| 159 | return $answer; |
| 160 | } |
| 161 | catch ( Exception $e ) { |
| 162 | error_log( $e->getMessage() ); |
| 163 | throw new Exception( 'Error while calling OpenAI: ' . $e->getMessage() ); |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | // Request to DALL-E API |
| 168 | public function runCreateImages( $query ) { |
| 169 | $this->applyQueryParameters( $query ); |
| 170 | $url = 'https://api.openai.com/v1/images/generations'; |
| 171 | $options = array( |
| 172 | "headers" => "Content-Type: application/json\r\n" . "Authorization: Bearer " . $query->apiKey . "\r\n", |
| 173 | "method" => "POST", |
| 174 | "timeout" => 120, |
| 175 | "body" => json_encode( array( |
| 176 | "prompt" => $query->prompt, |
| 177 | "n" => $query->maxResults, |
| 178 | "size" => '1024x1024', |
| 179 | ) ), |
| 180 | "sslverify" => false |
| 181 | ); |
| 182 | |
| 183 | try { |
| 184 | $response = wp_remote_get( $url, $options ); |
| 185 | if ( is_wp_error( $response ) ) { |
| 186 | throw new Exception( $response->get_error_message() ); |
| 187 | } |
| 188 | $response = wp_remote_retrieve_body( $response ); |
| 189 | $data = json_decode( $response, true ); |
| 190 | |
| 191 | // Error handling |
| 192 | if ( isset( $data['error'] ) ) { |
| 193 | $message = $data['error']['message']; |
| 194 | // If the message contains "Incorrect API key provided: THE_KEY.", replace the key by "----". |
| 195 | if ( preg_match( '/API key provided(: .*)\./', $message, $matches ) ) { |
| 196 | $message = str_replace( $matches[1], '', $message ); |
| 197 | } |
| 198 | throw new Exception( $message ); |
| 199 | } |
| 200 | |
| 201 | $answer = new Meow_MWAI_Answer( $query ); |
| 202 | $usage = $this->core->record_images_usage( "dall-e", "1024x1024", $query->maxResults ); |
| 203 | $answer->setUsage( $usage ); |
| 204 | $answer->setChoices( $data['data'] ); |
| 205 | return $answer; |
| 206 | } |
| 207 | catch ( Exception $e ) { |
| 208 | error_log( $e->getMessage() ); |
| 209 | throw new Exception( 'Error while calling OpenAI: ' . $e->getMessage() ); |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | public function throwException( $message ) { |
| 214 | $message = apply_filters( 'mwai_ai_exception', $message ); |
| 215 | throw new Exception( $message ); |
| 216 | } |
| 217 | |
| 218 | public function run( $query ) { |
| 219 | |
| 220 | |
| 221 | if ( $this->localService === 'azure' && $query->mode === 'chat' ) { |
| 222 | |
| 223 | } |
| 224 | |
| 225 | // Check if the query is allowed |
| 226 | $limits = $this->core->get_option( 'limits' ); |
| 227 | $ok = apply_filters( 'mwai_ai_allowed', true, $query, $limits ); |
| 228 | if ( $ok !== true ) { |
| 229 | $message = is_string( $ok ) ? $ok : 'Unauthorized query.'; |
| 230 | $this->throwException( $message ); |
| 231 | } |
| 232 | |
| 233 | // Allow to modify the query |
| 234 | $query = apply_filters( 'mwai_ai_query', $query ); |
| 235 | $query->checkFix(); |
| 236 | |
| 237 | // Run the query |
| 238 | $answer = null; |
| 239 | try { |
| 240 | if ( $query instanceof Meow_MWAI_QueryText ) { |
| 241 | $answer = $this->runCompletion( $query ); |
| 242 | } |
| 243 | else if ( $query instanceof Meow_MWAI_QueryEmbed ) { |
| 244 | $answer = $this->runEmbedding( $query ); |
| 245 | } |
| 246 | else if ( $query instanceof Meow_MWAI_QueryImage ) { |
| 247 | $answer = $this->runCreateImages( $query ); |
| 248 | } |
| 249 | else if ( $query instanceof Meow_MWAI_QueryTranscribe ) { |
| 250 | $answer = $this->runTranscribe( $query ); |
| 251 | } |
| 252 | else { |
| 253 | $this->throwException( 'Invalid query.' ); |
| 254 | } |
| 255 | } |
| 256 | catch ( Exception $e ) { |
| 257 | $this->throwException( $e->getMessage() ); |
| 258 | } |
| 259 | |
| 260 | // Let's allow some modififications of the answer |
| 261 | $answer = apply_filters( 'mwai_ai_reply', $answer, $query ); |
| 262 | return $answer; |
| 263 | } |
| 264 | } |
| 265 |