array( 'label' => __( 'OpenAI-compatible endpoint', 'aeoora' ), 'api' => 'openai', 'base' => '', 'model' => '', 'models' => array(), 'key_url' => '', 'json' => true, 'optional' => true, 'editable' => true, ), 'ollama' => array( 'label' => __( 'Ollama (local, free)', 'aeoora' ), 'api' => 'openai', 'base' => 'http://localhost:11434/v1', 'model' => 'llama3.1', 'models' => array( 'llama3.1', 'qwen2.5', 'mistral', 'gemma2' ), 'key_url' => 'https://ollama.com/', 'json' => true, 'optional' => true, 'editable' => true, ), ); if ( self::core_available() ) { // WordPress 7.0+: the AI Client in core, using whatever service the // site owner connected under Settings → Connectors. Listed first, so // it is used whenever it is set up and no other provider was chosen. $providers = array( 'wordpress' => array( 'label' => __( 'WordPress AI (Settings → Connectors)', 'aeoora' ), 'api' => 'wordpress', 'base' => '', 'model' => '', 'models' => array(), 'key_url' => admin_url( 'options-connectors.php' ), 'json' => true, 'core' => true, ), ) + $providers; } if ( Aeoora_Cloud::ai_available() ) { // The site is connected to aeoora Cloud: its AI, on the owner's plan. // Requests go to aeoora Cloud with the site's connection, no key here. $providers = array( 'cloud' => array( 'label' => __( 'aeoora Cloud AI', 'aeoora' ), 'api' => 'cloud', 'base' => '', 'model' => '', 'models' => array(), 'key_url' => admin_url( 'admin.php?page=aeoora-cloud' ), 'json' => true, 'cloud' => true, ), ) + $providers; } return apply_filters( 'aeoora_ai_providers', $providers ); } /** * Is the WordPress AI Client (WordPress 7.0+) present? * * @return bool */ public static function core_available() { return function_exists( 'wp_ai_client_prompt' ) && function_exists( 'wp_supports_ai' ); } /** * Can the WordPress AI Client generate text on this site (a connector is * set up and AI isn't turned off)? Cached for ten minutes, because asking * may read the connected services' model lists. * * @param bool $fresh Ask again instead of using the cached answer. * @return bool */ public static function core_ready( $fresh = false ) { if ( ! self::core_available() || ! wp_supports_ai() ) { return false; } $cached = $fresh ? false : get_transient( 'aeoora_core_ai_ready' ); if ( false !== $cached ) { return 'yes' === $cached; } $ready = false; try { $ready = (bool) wp_ai_client_prompt( 'ping' )->is_supported_for_text_generation(); } catch ( Throwable $e ) { $ready = false; } set_transient( 'aeoora_core_ai_ready', $ready ? 'yes' : 'no', 10 * MINUTE_IN_SECONDS ); return $ready; } /** * Provider config with user overrides. * * @param string $id Provider id. * @return array|null */ public static function provider( $id ) { $all = self::providers(); if ( ! isset( $all[ $id ] ) ) { return null; } $p = $all[ $id ]; $models = (array) Aeoora_Settings::get( 'ai', 'models', array() ); $bases = (array) Aeoora_Settings::get( 'ai', 'base_urls', array() ); if ( ! empty( $models[ $id ] ) ) { $p['model'] = $models[ $id ]; } if ( ! empty( $p['editable'] ) && ! empty( $bases[ $id ] ) ) { $p['base'] = untrailingslashit( $bases[ $id ] ); } $p['id'] = $id; return $p; } /* -------------------------------------------------------------- keys */ /** * Encryption key derived from the site salts. * * @return string 32 bytes. */ private static function secret() { $material = ( defined( 'AEOORA_ENCRYPTION_KEY' ) ? AEOORA_ENCRYPTION_KEY : '' ) . wp_salt( 'secure_auth' ) . wp_salt( 'logged_in' ); return hash( 'sha256', 'aeoora|' . $material, true ); } /** * Encrypt. * * @param string $plain Plain text. * @return string */ private static function encrypt( $plain ) { if ( '' === $plain ) { return ''; } $key = self::secret(); if ( function_exists( 'sodium_crypto_secretbox' ) ) { $nonce = random_bytes( SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ); return 's1:' . base64_encode( $nonce . sodium_crypto_secretbox( $plain, $nonce, $key ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions } if ( function_exists( 'openssl_encrypt' ) ) { $iv = random_bytes( 12 ); $tag = ''; $ct = openssl_encrypt( $plain, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag ); if ( false !== $ct ) { return 'o1:' . base64_encode( $iv . $tag . $ct ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions } } return 'p0:' . base64_encode( $plain ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions } /** * Decrypt. * * @param string $stored Stored value. * @return string */ private static function decrypt( $stored ) { $stored = (string) $stored; if ( strlen( $stored ) < 4 ) { return ''; } $scheme = substr( $stored, 0, 3 ); $raw = base64_decode( substr( $stored, 3 ), true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions if ( false === $raw ) { return ''; } $key = self::secret(); if ( 's1:' === $scheme && function_exists( 'sodium_crypto_secretbox_open' ) ) { $nonce = substr( $raw, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ); $ct = substr( $raw, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ); $plain = sodium_crypto_secretbox_open( $ct, $nonce, $key ); return false === $plain ? '' : $plain; } if ( 'o1:' === $scheme && function_exists( 'openssl_decrypt' ) ) { $plain = openssl_decrypt( substr( $raw, 28 ), 'aes-256-gcm', $key, OPENSSL_RAW_DATA, substr( $raw, 0, 12 ), substr( $raw, 12, 16 ) ); return false === $plain ? '' : $plain; } if ( 'p0:' === $scheme ) { return $raw; } return ''; } /** * Encrypt another credential the same way as provider keys (aeoora Cloud's * connection secret). * * @param string $plain Plain text. * @return string */ public static function seal( $plain ) { return self::encrypt( (string) $plain ); } /** * Decrypt a value made by seal(). '' when it can't be read (salts changed). * * @param string $stored Stored value. * @return string */ public static function unseal( $stored ) { return self::decrypt( $stored ); } /** * Get a provider key (constant AEOORA_KEY_ wins). * * @param string $provider Provider id. * @return string */ public static function get_key( $provider ) { $const = 'AEOORA_KEY_' . strtoupper( $provider ); if ( defined( $const ) ) { return (string) constant( $const ); } $keys = get_option( self::KEYS_OPTION, array() ); return isset( $keys[ $provider ] ) ? self::decrypt( $keys[ $provider ] ) : ''; } /** * Store (or delete with '') a provider key. * * @param string $provider Provider id. * @param string $key Key. */ public static function set_key( $provider, $key ) { $keys = get_option( self::KEYS_OPTION, array() ); $keys = is_array( $keys ) ? $keys : array(); $key = trim( preg_replace( '/\s+/', '', (string) $key ) ); if ( '' === $key ) { unset( $keys[ $provider ] ); } else { $keys[ $provider ] = self::encrypt( $key ); } update_option( self::KEYS_OPTION, $keys, false ); } /** * Is the provider usable? * * @param string $provider Provider id. * @return bool */ public static function is_ready( $provider ) { $p = self::provider( $provider ); if ( $p && ! empty( $p['core'] ) ) { return self::core_ready(); } if ( $p && ! empty( $p['cloud'] ) ) { return Aeoora_Cloud::ai_available(); } if ( ! $p || '' === $p['base'] || '' === $p['model'] ) { return false; } if ( '' !== self::get_key( $provider ) ) { return true; } // Keyless providers (Ollama, custom) count as ready once the owner saved their endpoint. $bases = (array) Aeoora_Settings::get( 'ai', 'base_urls', array() ); return ! empty( $p['optional'] ) && ! empty( $bases[ $provider ] ); } /** * Any provider configured? * * @return string Provider id to use, or ''. */ public static function default_provider() { $preferred = (string) Aeoora_Settings::get( 'ai', 'provider', 'wordpress' ); if ( self::is_ready( $preferred ) ) { return $preferred; } foreach ( array_keys( self::providers() ) as $id ) { if ( self::is_ready( $id ) ) { return $id; } } return ''; } /** * Masked key for display. * * @param string $provider Provider. * @return string */ public static function masked( $provider ) { $key = self::get_key( $provider ); if ( '' === $key ) { return ''; } return substr( $key, 0, 4 ) . str_repeat( '•', 8 ) . substr( $key, -4 ); } /* ---------------------------------------------------------- requests */ /** * Run a completion. * * @param array $args { * @type string $system System prompt. * @type string $prompt User prompt. * @type bool $json Expect a JSON object. * @type int $max_tokens Max output tokens. * @type float $temperature Temperature. * @type string $provider Provider id (default setting). * @type string $model Model override. * } * @return array|WP_Error { text, data (when json), provider, model, usage } */ public static function complete( array $args ) { $args = wp_parse_args( $args, array( 'system' => '', 'prompt' => '', 'json' => false, 'max_tokens' => (int) Aeoora_Settings::get( 'ai', 'max_tokens', 4096 ), 'temperature' => (float) Aeoora_Settings::get( 'ai', 'temperature', 0.7 ), 'provider' => '', 'model' => '', 'context' => 'manual', ) ); $provider_id = $args['provider'] ? $args['provider'] : self::default_provider(); if ( '' === $provider_id || ! self::is_ready( $provider_id ) ) { return new WP_Error( 'aeoora_ai_not_configured', self::core_available() ? __( 'Connect this site to aeoora Cloud, connect an AI service under Settings → Connectors, or enter an OpenAI-compatible endpoint in aeoora → Settings → AI.', 'aeoora' ) : __( 'Connect this site to aeoora Cloud, or enter an OpenAI-compatible endpoint (or a local Ollama server) in aeoora → Settings → AI first.', 'aeoora' ) ); } if ( ! self::within_limit() ) { return new WP_Error( 'aeoora_ai_limit', __( 'The daily AI request limit set in aeoora settings has been reached.', 'aeoora' ) ); } $p = self::provider( $provider_id ); if ( $args['model'] ) { $p['model'] = sanitize_text_field( $args['model'] ); } if ( $args['json'] ) { $args['system'] .= "\n\nReply with one valid JSON object and nothing else: no Markdown fences, no comments, no text before or after it. Escape quotes and line breaks inside strings."; // Room for the whole object: a reply cut off mid-way is never valid JSON. $args['max_tokens'] = max( (int) $args['max_tokens'], 4096 ); } if ( function_exists( 'set_time_limit' ) ) { @set_time_limit( 300 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors, Squiz.PHP.DiscouragedFunctions.Discouraged -- long-running admin task. } // Count the attempt before calling: failed requests count toward the // daily limit too, so a failing provider cannot be called endlessly. $result = self::send( $provider_id, $p, $args ); if ( is_wp_error( $result ) ) { return $result; } if ( $args['json'] ) { $data = self::parse_json( $result['text'] ); if ( null === $data && self::within_limit() ) { // One more try: twice the room if the reply was cut off, a cooler // temperature, and an even plainer format rule. $retry = $args; $retry['max_tokens'] = (int) $args['max_tokens'] * ( $result['truncated'] ? 2 : 1 ); $retry['temperature'] = min( 0.3, (float) $args['temperature'] ); $retry['system'] .= "\n\nYour previous reply could not be parsed as JSON. Keep every string short and return only the JSON object."; $again = self::send( $provider_id, $p, $retry ); if ( ! is_wp_error( $again ) ) { $result = $again; $data = self::parse_json( $result['text'] ); } } if ( null === $data ) { $message = $result['truncated'] ? __( 'The AI’s reply was cut off before it finished. Try a shorter length, or raise “Max output tokens” in aeoora → Settings → AI.', 'aeoora' ) : __( 'The AI’s reply wasn’t valid JSON, even after a second try. Try again, or choose a more capable model.', 'aeoora' ); return new WP_Error( 'aeoora_ai_bad_json', $message, array( 'raw' => $result['text'] ) ); } $result['data'] = $data; } return $result; } /** * One request to the provider, counted toward the daily limit before it is * made (so a failing provider cannot be called endlessly). * * @param string $provider_id Provider id. * @param array $p Provider config. * @param array $args Completion args. * @return array|WP_Error { text, usage, model, provider, provider_label, truncated } */ private static function send( $provider_id, array $p, array $args ) { self::track_usage( $provider_id, array(), true ); if ( 'cloud' === $p['api'] ) { $result = Aeoora_Cloud::ai_complete( $args ); } elseif ( 'wordpress' === $p['api'] ) { $result = self::call_wordpress( $args ); } else { $result = self::call_openai( $p, $args ); } if ( is_wp_error( $result ) ) { return $result; } self::track_usage( $provider_id, $result['usage'] ); $result['provider'] = $provider_id; $result['provider_label'] = $p['label']; $result['model'] = isset( $result['model'] ) ? $result['model'] : $p['model']; $result['truncated'] = ! empty( $result['truncated'] ); return $result; } /** * The WordPress AI Client (WordPress 7.0+): the service, model and * credentials are the site's (Settings → Connectors); aeoora never sees a key. * * @param array $args Args. * @return array|WP_Error */ private static function call_wordpress( array $args ) { if ( ! self::core_available() ) { return new WP_Error( 'aeoora_ai_not_configured', __( 'This WordPress version has no built-in AI Client.', 'aeoora' ) ); } $attempt = function ( $temperature ) use ( $args ) { $builder = wp_ai_client_prompt( (string) $args['prompt'] ); if ( '' !== (string) $args['system'] ) { $builder = $builder->using_system_instruction( (string) $args['system'] ); } $builder = $builder->using_max_tokens( max( 16, (int) $args['max_tokens'] ) ); if ( $temperature ) { $builder = $builder->using_temperature( (float) $args['temperature'] ); } return $builder->generate_text_result(); }; try { $result = $attempt( true ); // Some models take no temperature: ask again without it. if ( is_wp_error( $result ) && false !== stripos( $result->get_error_message(), 'temperature' ) ) { $result = $attempt( false ); } } catch ( Throwable $e ) { $result = new WP_Error( 'aeoora_ai_api', $e->getMessage() ); } if ( is_wp_error( $result ) ) { delete_transient( 'aeoora_core_ai_ready' ); // Its connector may have gone: check again next time. /* translators: %s: error message from WordPress. */ return new WP_Error( 'aeoora_ai_api', sprintf( __( 'WordPress AI couldn’t answer: %s', 'aeoora' ), $result->get_error_message() ) ); } $usage = $result->getTokenUsage(); $model = $result->getModelMetadata(); $candidates = $result->getCandidates(); return array( 'text' => self::strip_thinking( (string) $result->toText() ), 'model' => trim( $result->getProviderMetadata()->getName() . ' / ' . $model->getName(), ' /' ), 'truncated' => $candidates && 'length' === (string) $candidates[0]->getFinishReason(), 'usage' => array( 'in' => (int) $usage->getPromptTokens(), 'out' => (int) $usage->getCompletionTokens(), ), ); } /** * OpenAI-compatible chat completions (with automatic parameter fallbacks). * * @param array $p Provider. * @param array $args Args. * @return array|WP_Error */ private static function call_openai( array $p, array $args ) { $messages = array(); if ( '' !== $args['system'] ) { $messages[] = array( 'role' => 'system', 'content' => $args['system'], ); } $messages[] = array( 'role' => 'user', 'content' => $args['prompt'], ); // Reasoning models ("o3", "gpt-5", "openai/gpt-5-mini" …) take max_completion_tokens, // spend part of it thinking, and refuse a temperature. $reasoning = (bool) preg_match( '~(^|/)(o\d|gpt-5)~i', $p['model'] ); $body = array( 'model' => $p['model'], 'messages' => $messages, ); if ( $reasoning ) { $body['max_completion_tokens'] = (int) $args['max_tokens'] * 2; } else { $body['max_tokens'] = (int) $args['max_tokens']; } if ( ! $reasoning ) { $body['temperature'] = (float) $args['temperature']; } if ( $args['json'] && ! empty( $p['json'] ) ) { $body['response_format'] = array( 'type' => 'json_object' ); } $headers = array( 'Content-Type' => 'application/json' ); $key = self::get_key( $p['id'] ); if ( '' !== $key ) { $headers['Authorization'] = 'Bearer ' . $key; } $url = $p['base'] . '/chat/completions'; for ( $attempt = 0; $attempt < 3; $attempt++ ) { $res = self::post( $url, $headers, $body ); if ( ! is_wp_error( $res ) ) { break; } $msg = strtolower( $res->get_error_message() ); // Drop parameters this model/provider rejects and retry. if ( isset( $body['response_format'] ) && ( false !== strpos( $msg, 'response_format' ) || false !== strpos( $msg, 'json' ) ) ) { unset( $body['response_format'] ); } elseif ( isset( $body['temperature'] ) && false !== strpos( $msg, 'temperature' ) ) { unset( $body['temperature'] ); } elseif ( isset( $body['max_completion_tokens'] ) && false !== strpos( $msg, 'max_completion_tokens' ) ) { $body['max_tokens'] = $body['max_completion_tokens']; unset( $body['max_completion_tokens'] ); } elseif ( isset( $body['max_tokens'] ) && false !== strpos( $msg, 'max_tokens' ) ) { $body['max_completion_tokens'] = $body['max_tokens']; unset( $body['max_tokens'] ); } else { return $res; } } if ( is_wp_error( $res ) ) { return $res; } $text = isset( $res['choices'][0]['message']['content'] ) ? $res['choices'][0]['message']['content'] : ''; if ( is_array( $text ) ) { $text = implode( '', wp_list_pluck( $text, 'text' ) ); } $text = self::strip_thinking( (string) $text ); return array( 'text' => $text, 'truncated' => isset( $res['choices'][0]['finish_reason'] ) && 'length' === $res['choices'][0]['finish_reason'], 'usage' => array( 'in' => isset( $res['usage']['prompt_tokens'] ) ? (int) $res['usage']['prompt_tokens'] : 0, 'out' => isset( $res['usage']['completion_tokens'] ) ? (int) $res['usage']['completion_tokens'] : 0, ), 'citations' => isset( $res['citations'] ) ? (array) $res['citations'] : array(), ); } /** * POST JSON and decode, turning API errors into WP_Error. * * @param string $url URL. * @param array $headers Headers. * @param array $body Body. * @return array|WP_Error */ private static function post( $url, array $headers, array $body ) { $res = wp_remote_post( $url, array( // Background jobs give up sooner, so one slow answer never eats a cron run. 'timeout' => (int) apply_filters( 'aeoora_ai_timeout', wp_doing_cron() ? 60 : 180 ), 'headers' => $headers, 'body' => wp_json_encode( $body ), 'data_format' => 'body', 'user-agent' => 'aeoora/' . AEOORA_VERSION . '; WordPress', ) ); if ( is_wp_error( $res ) ) { return new WP_Error( 'aeoora_ai_http', sprintf( /* translators: %s: error. */ __( 'Could not reach the AI provider: %s', 'aeoora' ), $res->get_error_message() ) ); } $code = (int) wp_remote_retrieve_response_code( $res ); $data = json_decode( (string) wp_remote_retrieve_body( $res ), true ); if ( $code < 200 || $code >= 300 ) { $msg = ''; if ( is_array( $data ) ) { if ( isset( $data['error']['message'] ) ) { $msg = $data['error']['message']; } elseif ( isset( $data['error'] ) && is_string( $data['error'] ) ) { $msg = $data['error']; } elseif ( isset( $data['message'] ) ) { $msg = $data['message']; } elseif ( isset( $data[0]['error']['message'] ) ) { $msg = $data[0]['error']['message']; } } if ( '' === $msg ) { $msg = wp_trim_words( wp_strip_all_tags( (string) wp_remote_retrieve_body( $res ) ), 30 ); } return new WP_Error( 'aeoora_ai_api', sprintf( /* translators: 1: HTTP code, 2: message. */ __( 'AI provider error (HTTP %1$d): %2$s', 'aeoora' ), $code, $msg ), array( 'status' => $code ) ); } if ( ! is_array( $data ) ) { return new WP_Error( 'aeoora_ai_parse', __( 'Unexpected response from the AI provider.', 'aeoora' ) ); } return $data; } /** * Remove blocks some reasoning models emit. * * @param string $text Text. * @return string */ private static function strip_thinking( $text ) { $out = preg_replace( '~.*?~is', '', $text ); return trim( null === $out ? $text : $out ); } /** * Lenient JSON extraction. Accepts what models really send: code fences, * prose around the object, raw line breaks inside strings, trailing commas, * invalid escapes, and replies cut off before the end (closed here, so the * complete fields are kept). * * @param string $text Text. * @return array|null Decoded object (a top-level list becomes { items: [...] }), or null. */ public static function parse_json( $text ) { $text = trim( (string) $text ); $text = preg_replace( '~^\xEF\xBB\xBF~', '', $text ); if ( preg_match( '~```(?:json|JSON)?\s*(.+?)(?:```|$)~s', $text, $m ) ) { $text = trim( $m[1] ); } $data = json_decode( $text, true ); if ( ! is_array( $data ) ) { $data = json_decode( self::repair_json( $text ), true ); } if ( ! is_array( $data ) ) { return null; } return array_keys( $data ) === range( 0, count( $data ) - 1 ) && $data ? array( 'items' => $data ) : $data; } /** * Best-effort repair of a model's JSON: starts at the first { or [, stops * after the matching close (dropping trailing prose), escapes raw control * characters inside strings, drops invalid escapes and trailing commas, and * closes whatever a cut-off reply left open. * * @param string $text Text. * @return string JSON (possibly still invalid). */ public static function repair_json( $text ) { $text = (string) $text; $start = strcspn( $text, '{[' ); if ( $start >= strlen( $text ) ) { return ''; } $text = substr( $text, $start ); $len = strlen( $text ); $out = ''; $stack = array(); $in = false; $esc = false; for ( $i = 0; $i < $len; $i++ ) { $c = $text[ $i ]; if ( $in ) { if ( $esc ) { $esc = false; if ( false === strpos( '"\\/bfnrtu', $c ) ) { $out = substr( $out, 0, -1 ); // "\'" and other invalid escapes: keep the character. } $out .= $c; } elseif ( '\\' === $c ) { $esc = true; $out .= $c; } elseif ( '"' === $c ) { $in = false; $out .= $c; } elseif ( "\n" === $c ) { $out .= '\n'; } elseif ( "\r" === $c ) { $out .= '\r'; } elseif ( "\t" === $c ) { $out .= '\t'; } elseif ( ord( $c ) >= 0x20 ) { $out .= $c; } continue; } if ( '"' === $c ) { $in = true; $out .= $c; } elseif ( '{' === $c || '[' === $c ) { $stack[] = '{' === $c ? '}' : ']'; $out .= $c; } elseif ( '}' === $c || ']' === $c ) { $out = preg_replace( '~,\s*$~', '', rtrim( $out ) ); array_pop( $stack ); $out .= $c; if ( ! $stack ) { break; // The whole value is closed: ignore anything after it. } } else { $out .= $c; } } if ( ! $stack ) { return $out; } // Cut off: finish the open string, drop a dangling key or separator, then close. if ( $in ) { if ( $esc ) { $out = substr( $out, 0, -1 ); } $out .= '"'; } $out = rtrim( $out ); if ( '}' === end( $stack ) ) { $out = preg_replace( '~([{,])\s*"(?:[^"\\\\]|\\\\.)*"\s*$~', '$1', $out ); // A key without its value. } $out = preg_replace( '~:\s*$~', ': null', $out ); $out = preg_replace( '~([{\[,:]\s*)(?:t|tr|tru|f|fa|fal|fals|n|nu|nul)$~', '$1null', $out ); while ( $stack ) { $out = preg_replace( '~,\s*$~', '', rtrim( $out ) ); $out .= array_pop( $stack ); } return $out; } /** * List models available for a provider. * * @param string $provider Provider. * @return array|WP_Error */ public static function list_models( $provider ) { $p = self::provider( $provider ); if ( ! $p ) { return new WP_Error( 'aeoora_ai_provider', __( 'Unknown provider.', 'aeoora' ) ); } if ( ! empty( $p['core'] ) ) { return new WP_Error( 'aeoora_ai_models', __( 'WordPress AI uses the model of the service connected under Settings → Connectors.', 'aeoora' ) ); } if ( '' === $p['base'] ) { return new WP_Error( 'aeoora_ai_models', __( 'Save the endpoint address first.', 'aeoora' ) ); } $key = self::get_key( $provider ); $url = $p['base'] . '/models'; $headers = $key ? array( 'Authorization' => 'Bearer ' . $key ) : array(); $res = wp_remote_get( $url, array( 'timeout' => 20, 'headers' => $headers, ) ); if ( is_wp_error( $res ) ) { return $res; } $code = (int) wp_remote_retrieve_response_code( $res ); $data = json_decode( (string) wp_remote_retrieve_body( $res ), true ); if ( 200 !== $code || ! is_array( $data ) ) { return new WP_Error( 'aeoora_ai_models', sprintf( /* translators: %d: HTTP code. */ __( 'Could not list models (HTTP %d). Check the API key.', 'aeoora' ), $code ) ); } $ids = array(); $list = isset( $data['data'] ) ? $data['data'] : ( isset( $data['models'] ) ? $data['models'] : $data ); foreach ( (array) $list as $m ) { if ( is_array( $m ) && isset( $m['id'] ) ) { $ids[] = (string) $m['id']; } elseif ( is_array( $m ) && isset( $m['name'] ) ) { $ids[] = (string) $m['name']; } } $ids = array_values( array_unique( array_filter( $ids ) ) ); sort( $ids ); return $ids; } /** * Test a provider with a tiny request. * * @param string $provider Provider. * @return array|WP_Error */ public static function test( $provider ) { if ( 'wordpress' === $provider ) { self::core_ready( true ); // A connector may have been set up a moment ago. } $start = microtime( true ); $res = self::complete( array( 'provider' => $provider, 'system' => 'You are a connection test.', 'prompt' => 'Reply with exactly: aeoora OK', 'max_tokens' => 50, 'temperature' => 0, 'context' => 'test', ) ); if ( is_wp_error( $res ) ) { return $res; } return array( 'ok' => true, 'reply' => wp_trim_words( $res['text'], 12 ), 'model' => $res['model'], 'ms' => (int) round( ( microtime( true ) - $start ) * 1000 ), ); } /* ------------------------------------------------------------- usage */ /** * Within the daily request limit? * * @return bool */ private static function within_limit() { $limit = (int) Aeoora_Settings::get( 'ai', 'daily_limit', 200 ); if ( $limit <= 0 ) { return true; } $usage = self::usage(); $today = wp_date( 'Y-m-d' ); return empty( $usage[ $today ]['requests'] ) || $usage[ $today ]['requests'] < $limit; } /** * Track usage per day / provider: the request when it starts, the tokens * when it succeeds. * * @param string $provider Provider. * @param array $usage Usage (in, out tokens). * @param bool $request Count a request (else only add tokens). */ private static function track_usage( $provider, array $usage, $request = false ) { $all = self::usage(); $today = wp_date( 'Y-m-d' ); if ( ! isset( $all[ $today ] ) ) { $all[ $today ] = array( 'requests' => 0, 'in' => 0, 'out' => 0, 'providers' => array(), ); } if ( $request ) { $all[ $today ]['requests']++; $all[ $today ]['providers'][ $provider ] = ( isset( $all[ $today ]['providers'][ $provider ] ) ? $all[ $today ]['providers'][ $provider ] : 0 ) + 1; } $all[ $today ]['in'] += isset( $usage['in'] ) ? (int) $usage['in'] : 0; $all[ $today ]['out'] += isset( $usage['out'] ) ? (int) $usage['out'] : 0; $all = array_slice( $all, -60, 60, true ); update_option( self::USAGE_OPTION, $all, false ); } /** * Usage log. * * @return array */ public static function usage() { $u = get_option( self::USAGE_OPTION, array() ); return is_array( $u ) ? $u : array(); } }