$target ) { $tests[] = self::describe_connection_test_target( $id, $target ); } return $tests; } /** * Runs one connection test by the ID handed out by get_connection_tests(). * * Text models get a real (tiny) completion so billing and quota problems * surface. Image models only get a model lookup — generating a test image * would cost real money. * * @param string $id * @return array|WP_Error The test description plus `ok` and `error` (see explain_provider_error()). */ public static function run_connection_test( $id ) { $targets = self::get_connection_test_targets(); if ( ! isset( $targets[ $id ] ) ) { return new WP_Error( 'unknown_connection_test', __( 'Your AI settings changed since this page loaded. Reload the page and test again.', 'ai-content-generator-for-woocommerce' ) ); } $target = $targets[ $id ]; $timeout = absint( get_option( 'wtofe_ai_request_timeout', 30 ) ); if ( $timeout < 10 ) { $timeout = 60; } $response = 'image' === $target['kind'] ? self::probe_model_availability( $target['provider'], $target['api_key'], $target['model'], $timeout ) : self::probe_text_generation( $target['provider'], $target['api_key'], $target['model'], $timeout ); $code = is_wp_error( $response ) ? 0 : (int) wp_remote_retrieve_response_code( $response ); self::log_debug( 'Connection test response', array( 'provider' => $target['provider'], 'model' => $target['model'], 'code' => $code, 'body' => is_wp_error( $response ) ? $response->get_error_message() : wp_remote_retrieve_body( $response ), ) ); $result = self::describe_connection_test_target( $id, $target ); $result['ok'] = $code >= 200 && $code < 300; $result['error'] = $result['ok'] ? null : self::explain_provider_error( $target['provider'], $response, array( 'model' => $target['model'], 'source' => $target['source'], 'features' => array_keys( $target['features'] ), 'timeout' => $timeout, ) ); return $result; } /** * Turns a failed provider response into a category, a plain-language * message, and links to where the user can fix it. * * Categories: invalid_key, quota, model_unavailable, timeout, unknown. * * @param string $provider 'openai', 'google', or 'anthropic'. * @param array|WP_Error $response Raw wp_remote_*() result. * @param array $context Optional: model, source ('custom'|'connector'), features (keys), timeout. * @return array{category: string, http_code: int, provider: string, title: string, message: string, details: string, links: array[]} */ public static function explain_provider_error( $provider, $response, array $context = array() ) { $label = self::get_provider_label( $provider ); $urls = self::get_provider_fix_urls( $provider ); $model = isset( $context['model'] ) ? (string) $context['model'] : ''; $code = 0; $raw = ''; $signals = array(); if ( is_wp_error( $response ) ) { $raw = $response->get_error_message(); } else { $code = (int) wp_remote_retrieve_response_code( $response ); $body = json_decode( wp_remote_retrieve_body( $response ), true ); $error = is_array( $body ) && isset( $body['error'] ) && is_array( $body['error'] ) ? $body['error'] : array(); $raw = isset( $error['message'] ) ? (string) $error['message'] : ''; // Machine-readable bits: OpenAI type/code, Anthropic type, Gemini status and detail reasons. foreach ( array( 'type', 'code', 'status' ) as $field ) { if ( isset( $error[ $field ] ) && is_scalar( $error[ $field ] ) ) { $signals[] = (string) $error[ $field ]; } } if ( isset( $error['details'] ) && is_array( $error['details'] ) ) { foreach ( $error['details'] as $detail ) { if ( isset( $detail['reason'] ) && is_scalar( $detail['reason'] ) ) { $signals[] = (string) $detail['reason']; } } } } $haystack = strtolower( $raw . ' ' . implode( ' ', $signals ) ); if ( is_wp_error( $response ) ) { $category = preg_match( '/timed out|curl error 28/', $haystack ) ? 'timeout' : 'unknown'; } elseif ( in_array( $code, array( 408, 504, 524 ), true ) || false !== strpos( $haystack, 'deadline_exceeded' ) ) { $category = 'timeout'; } elseif ( 429 === $code || preg_match( '/insufficient_quota|billing|credit balance|quota|resource_exhausted/', $haystack ) ) { $category = 'quota'; } elseif ( 401 === $code || preg_match( '/invalid_api_key|api_key_invalid|api key not valid|incorrect api key|invalid x-api-key|authentication_error|unauthenticated/', $haystack ) ) { $category = 'invalid_key'; } elseif ( 404 === $code || preg_match( '/model_not_found|does not exist|not_found_error|is not found|not a chat model|must be verified/', $haystack ) ) { $category = 'model_unavailable'; } elseif ( 403 === $code && ! preg_match( '/country|region|territory|location/', $haystack ) ) { $category = 'invalid_key'; } else { $category = 'unknown'; } $links = array(); switch ( $category ) { case 'invalid_key': $title = __( 'Invalid API key', 'ai-content-generator-for-woocommerce' ); /* translators: %s: provider name, e.g. OpenAI */ $message = sprintf( __( '%s rejected the API key. It may be mistyped, revoked, or missing permissions.', 'ai-content-generator-for-woocommerce' ), $label ); if ( isset( $context['source'] ) && 'custom' === $context['source'] ) { $links[] = self::fix_link( __( 'Replace the key', 'ai-content-generator-for-woocommerce' ), '#wtofe-api-key-row' ); } elseif ( self::has_ai_connectors_screen() ) { $links[] = self::fix_link( __( 'Update the key in Settings → Connectors', 'ai-content-generator-for-woocommerce' ), admin_url( 'options-connectors.php' ) ); } /* translators: %s: provider name, e.g. OpenAI */ $links[] = self::fix_link( sprintf( __( 'Create a new %s key', 'ai-content-generator-for-woocommerce' ), $label ), $urls['keys'], true ); break; case 'quota': $title = __( 'No billing or quota left', 'ai-content-generator-for-woocommerce' ); /* translators: %s: provider name, e.g. OpenAI */ $message = sprintf( __( '%s refused the request because the account has no billing set up, has run out of credit, or has hit its usage limit.', 'ai-content-generator-for-woocommerce' ), $label ); $links[] = self::fix_link( __( 'Add billing or credit', 'ai-content-generator-for-woocommerce' ), $urls['billing'], true ); $links[] = self::fix_link( __( 'Check usage limits', 'ai-content-generator-for-woocommerce' ), $urls['limits'], true ); break; case 'model_unavailable': $title = __( 'Model unavailable', 'ai-content-generator-for-woocommerce' ); $message = '' !== $model /* translators: 1: provider name, 2: model ID */ ? sprintf( __( '%1$s doesn\'t offer %2$s to this API key. The model may be retired, misspelled, or need extra account access.', 'ai-content-generator-for-woocommerce' ), $label, $model ) /* translators: %s: provider name, e.g. OpenAI */ : sprintf( __( '%s doesn\'t offer the requested model to this API key.', 'ai-content-generator-for-woocommerce' ), $label ); $features = isset( $context['features'] ) ? (array) $context['features'] : array(); $links[] = self::fix_link( __( 'Choose a different model', 'ai-content-generator-for-woocommerce' ), self::get_model_field_anchor( reset( $features ) ) ); /* translators: %s: provider name, e.g. OpenAI */ $links[] = self::fix_link( sprintf( __( 'See available %s models', 'ai-content-generator-for-woocommerce' ), $label ), $urls['models'], true ); break; case 'timeout': $title = __( 'Request timed out', 'ai-content-generator-for-woocommerce' ); $message = isset( $context['timeout'] ) /* translators: 1: provider name, 2: number of seconds */ ? sprintf( __( '%1$s didn\'t respond within %2$d seconds.', 'ai-content-generator-for-woocommerce' ), $label, (int) $context['timeout'] ) /* translators: %s: provider name, e.g. OpenAI */ : sprintf( __( '%s didn\'t respond in time.', 'ai-content-generator-for-woocommerce' ), $label ); $links[] = self::fix_link( __( 'Increase the request timeout', 'ai-content-generator-for-woocommerce' ), '#wtofe_ai_request_timeout' ); /* translators: %s: provider name, e.g. OpenAI */ $links[] = self::fix_link( sprintf( __( 'Check %s status', 'ai-content-generator-for-woocommerce' ), $label ), $urls['status'], true ); break; default: $title = __( 'Connection failed', 'ai-content-generator-for-woocommerce' ); if ( is_wp_error( $response ) ) { /* translators: %s: provider name, e.g. OpenAI */ $message = sprintf( __( 'Your server couldn\'t reach %s.', 'ai-content-generator-for-woocommerce' ), $label ); } elseif ( $code >= 500 ) { /* translators: 1: provider name, 2: HTTP status code */ $message = sprintf( __( '%1$s is having problems right now (HTTP %2$d). Try again in a few minutes.', 'ai-content-generator-for-woocommerce' ), $label, $code ); } else { /* translators: 1: provider name, 2: HTTP status code */ $message = sprintf( __( '%1$s returned an unexpected error (HTTP %2$d).', 'ai-content-generator-for-woocommerce' ), $label, $code ); } /* translators: %s: provider name, e.g. OpenAI */ $links[] = self::fix_link( sprintf( __( 'Check %s status', 'ai-content-generator-for-woocommerce' ), $label ), $urls['status'], true ); break; } return array( 'category' => $category, 'http_code' => $code, 'provider' => $label, 'title' => $title, 'message' => $message, 'details' => wp_html_excerpt( $raw, 300, '…' ), 'links' => $links, ); } /** * Payload for wp_send_json_error(): the error message, plus fix links and * the provider's own wording when the error came from provider_error(). * * These errors show up outside the settings page, so in-page anchors become * links to it. Admin links the current user can't open are dropped. * * @param WP_Error $error * @return array{message: string, provider?: string, details?: string, links?: array[]} */ public static function get_error_response_data( WP_Error $error ) { $data = array( 'message' => $error->get_error_message() ); $error_data = $error->get_error_data(); if ( ! is_array( $error_data ) || empty( $error_data['explained'] ) ) { return $data; } $explained = $error_data['explained']; $settings_url = admin_url( 'admin.php?page=wc-ai-content-generator' ); $data['provider'] = $explained['provider']; $data['details'] = $explained['details']; $data['links'] = array(); foreach ( $explained['links'] as $link ) { if ( ! $link['external'] ) { // Internal links are settings-page anchors, the setup wizard // (both manage_woocommerce) or Settings → Connectors. $is_anchor = 0 === strpos( $link['url'], '#' ); $is_plugin = $is_anchor || WTOFE_Setup_Wizard::get_url() === $link['url']; if ( ! current_user_can( $is_plugin ? 'manage_woocommerce' : 'manage_options' ) ) { continue; } if ( $is_anchor ) { $link['url'] = $settings_url . $link['url']; } } $data['links'][] = $link; } return $data; } /** * The same explanation as get_error_response_data(), as HTML for places * that render markup directly (the admin chatbot). * * @param WP_Error $error * @return string */ public static function get_error_html( WP_Error $error ) { $data = self::get_error_response_data( $error ); $error_data = $error->get_error_data(); if ( ! isset( $data['links'] ) || ! is_array( $error_data ) ) { return esc_html( $data['message'] ); } $explained = $error_data['explained']; $html = '' . esc_html( $explained['title'] ) . '. ' . esc_html( $explained['message'] ); $links = array(); foreach ( $data['links'] as $link ) { $links[] = '' . esc_html( $link['label'] ) . ''; } if ( $links ) { $html .= '
' . implode( ' · ', $links ); } return $html; } /** * WP_Error for a failed provider call. The message is the plain-language * explanation; the full explain_provider_error() result rides along as * error data for get_error_response_data(). * * @param string $provider * @param array|WP_Error $response Raw wp_remote_*() result. * @param array $context See explain_provider_error(). * @return WP_Error */ private static function provider_error( $provider, $response, array $context = array() ) { $explained = self::explain_provider_error( $provider, $response, $context ); return new WP_Error( 'api_error', $explained['title'] . '. ' . $explained['message'], array( 'explained' => $explained ) ); } /** * WP_Error for when no API key resolves for a feature, with fix links in * the same shape as provider_error(). Usually nothing is connected at all; * otherwise the feature's saved model belongs to a provider without a key * (the custom ChatGPT API key only covers OpenAI models). * * @param string $feature e.g. 'description', 'image_generation'. Empty for generic use. * @return WP_Error */ public static function missing_provider_error( $feature = '' ) { if ( self::has_active_connector() ) { $title = __( 'Model not available', 'ai-content-generator-for-woocommerce' ); $message = __( 'The model chosen for this feature is from an AI provider that isn\'t connected.', 'ai-content-generator-for-woocommerce' ); $links = array( self::fix_link( __( 'Choose a different model', 'ai-content-generator-for-woocommerce' ), self::get_model_field_anchor( $feature ) ) ); } else { $title = __( 'No AI provider connected', 'ai-content-generator-for-woocommerce' ); // Before WordPress 7.0 the wizard can only add the plugin's own OpenAI key. $message = self::has_ai_connectors_screen() ? __( 'Connect OpenAI, Google or Anthropic in the setup wizard to start generating content.', 'ai-content-generator-for-woocommerce' ) : __( 'Add an OpenAI API key in the setup wizard to start generating content.', 'ai-content-generator-for-woocommerce' ); $links = array( self::fix_link( __( 'Run the setup wizard', 'ai-content-generator-for-woocommerce' ), WTOFE_Setup_Wizard::get_url() ) ); } return new WP_Error( 'missing_api_key', $title . '. ' . $message, array( 'explained' => array( 'category' => 'missing_key', 'http_code' => 0, 'provider' => '', 'title' => $title, 'message' => $message, 'details' => '', 'links' => $links, ), ) ); } /** * Whether a wp_remote_*() result failed at the transport or HTTP level. * * @param array|WP_Error $response * @return bool */ private static function is_failed_response( $response ) { if ( is_wp_error( $response ) ) { return true; } $code = (int) wp_remote_retrieve_response_code( $response ); return $code < 200 || $code >= 300; } /** * Error context for a real generation request, so fix links point at the * right key field and model dropdown. * * @param array{api_key: string, model: string} $credentials From get_provider_credentials(). * @param string $feature * @param int $timeout * @return array */ private static function get_request_error_context( array $credentials, $feature, $timeout ) { return array( 'model' => $credentials['model'], 'source' => self::get_key_source( $credentials['api_key'] ), 'features' => '' !== $feature ? array( $feature ) : array(), 'timeout' => $timeout, ); } /** * 'custom' when the key is this plugin's own (enabled) ChatGPT key, * otherwise 'connector'. * * @param string $api_key * @return string */ private static function get_key_source( $api_key ) { $custom_key = (bool) get_option( 'wtofe_use_custom_api_key', false ) ? trim( (string) get_option( 'wtofe_chatgpt_api_key', '' ) ) : ''; return ( '' !== $custom_key && $custom_key === $api_key ) ? 'custom' : 'connector'; } /** * Every distinct provider/key/model/kind combination the plugin will call, * keyed by an opaque ID. Resolved through get_provider_credentials() so the * test follows exactly the same routing as real generation requests. * * @return array}> */ private static function get_connection_test_targets() { $features = array( 'title' => __( 'Product name', 'ai-content-generator-for-woocommerce' ), 'description' => __( 'Description', 'ai-content-generator-for-woocommerce' ), 'short_description' => __( 'Short description', 'ai-content-generator-for-woocommerce' ), 'brands' => __( 'Brands', 'ai-content-generator-for-woocommerce' ), 'tags' => __( 'Tags', 'ai-content-generator-for-woocommerce' ), ); if ( class_exists( 'WTOFE_SEO_Meta_Provider_Registry' ) && WTOFE_SEO_Meta_Provider_Registry::is_any_active() ) { $features['meta'] = __( 'SEO meta', 'ai-content-generator-for-woocommerce' ); } if ( get_option( 'wtofe_chatbot_enabled', false ) ) { // Same mirroring the chatbot does before each reply, so the test // resolves the model the chatbot will really use. $chatbot_model = trim( (string) get_option( 'wtofe_chatbot_model', '' ) ); if ( get_option( 'wtofe_ai_model_chatbot', '' ) !== $chatbot_model ) { update_option( 'wtofe_ai_model_chatbot', $chatbot_model ); } $features['chatbot'] = __( 'Chatbot', 'ai-content-generator-for-woocommerce' ); } $features['image_generation'] = __( 'Images', 'ai-content-generator-for-woocommerce' ); $targets = array(); foreach ( $features as $feature => $feature_label ) { $credentials = self::get_provider_credentials( $feature ); if ( '' === $credentials['api_key'] ) { continue; } $kind = 'image_generation' === $feature ? 'image' : 'text'; // Anthropic has no image models; the settings page doesn't offer one either. if ( 'image' === $kind && 'anthropic' === $credentials['provider'] ) { continue; } $id = self::connection_test_target_id( $credentials['provider'], $credentials['api_key'], $credentials['model'], $kind ); if ( ! isset( $targets[ $id ] ) ) { $targets[ $id ] = array( 'provider' => $credentials['provider'], 'api_key' => $credentials['api_key'], 'model' => $credentials['model'], 'kind' => $kind, 'source' => self::get_key_source( $credentials['api_key'] ), 'features' => array(), ); } $targets[ $id ]['features'][ $feature ] = $feature_label; } // Keys no feature currently routes to still get a text check with the // provider's default model, so a bad key shows up before it's needed. $keys = array(); $custom_key = (bool) get_option( 'wtofe_use_custom_api_key', false ) ? trim( (string) get_option( 'wtofe_chatgpt_api_key', '' ) ) : ''; if ( '' !== $custom_key ) { $keys[] = array( 'openai', $custom_key, 'custom' ); } foreach ( array( 'openai', 'google', 'anthropic' ) as $provider ) { $connector_key = trim( (string) get_option( self::get_connector_option_for_provider( $provider ), '' ) ); if ( '' !== $connector_key ) { $keys[] = array( $provider, $connector_key, 'connector' ); } } foreach ( $keys as $key ) { list( $provider, $api_key, $source ) = $key; foreach ( $targets as $target ) { if ( 'text' === $target['kind'] && $target['api_key'] === $api_key ) { continue 2; } } $model = self::get_default_model_for_provider( $provider ); $id = self::connection_test_target_id( $provider, $api_key, $model, 'text' ); $targets[ $id ] = array( 'provider' => $provider, 'api_key' => $api_key, 'model' => $model, 'kind' => 'text', 'source' => $source, 'features' => array(), ); } return $targets; } /** * Opaque, salted ID for a test target — safe to send to the browser. * * @return string */ private static function connection_test_target_id( $provider, $api_key, $model, $kind ) { return substr( wp_hash( $provider . '|' . $kind . '|' . $model . '|' . $api_key ), 0, 16 ); } /** * Browser-safe description of a test target (no API key). * * @return array */ private static function describe_connection_test_target( $id, array $target ) { return array( 'id' => $id, 'provider' => self::get_provider_label( $target['provider'] ), 'model' => $target['model'], 'source' => 'custom' === $target['source'] ? __( 'Custom API key', 'ai-content-generator-for-woocommerce' ) : __( 'AI Connector', 'ai-content-generator-for-woocommerce' ), 'features' => array_values( $target['features'] ), 'note' => 'image' === $target['kind'] ? __( 'Checks the key and model only. No image is generated.', 'ai-content-generator-for-woocommerce' ) : '', ); } /** * Sends the smallest possible chat request. Any 2xx counts as a pass, even * if a reasoning model spends the token budget before replying. * * @return array|WP_Error Raw wp_remote_post() result. */ private static function probe_text_generation( $provider, $api_key, $model, $timeout ) { $prompt = 'Reply with OK.'; if ( 'anthropic' === $provider ) { return wp_remote_post( 'https://api.anthropic.com/v1/messages', array( //phpcs:ignore PluginCheck.CodeAnalysis.AIProvider.DirectIntegration 'headers' => array( 'Content-Type' => 'application/json', 'x-api-key' => $api_key, 'anthropic-version' => '2023-06-01', ), 'body' => wp_json_encode( array( 'model' => $model, 'max_tokens' => 16, 'messages' => array( array( 'role' => 'user', 'content' => $prompt ) ), ) ), 'timeout' => $timeout, ) ); } if ( 'google' === $provider ) { return wp_remote_post( 'https://generativelanguage.googleapis.com/v1beta/models/' . $model . ':generateContent', array( //phpcs:ignore PluginCheck.CodeAnalysis.AIProvider.DirectIntegration 'headers' => array( 'Content-Type' => 'application/json', 'x-goog-api-key' => $api_key, ), 'body' => wp_json_encode( array( 'contents' => array( array( 'role' => 'user', 'parts' => array( array( 'text' => $prompt ) ) ) ), 'generationConfig' => array( 'maxOutputTokens' => 16 ), ) ), 'timeout' => $timeout, ) ); } return wp_remote_post( 'https://api.openai.com/v1/chat/completions', array( //phpcs:ignore PluginCheck.CodeAnalysis.AIProvider.DirectIntegration 'headers' => array( 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_key, ), 'body' => wp_json_encode( array( 'model' => $model, 'messages' => array( array( 'role' => 'user', 'content' => $prompt ) ), 'max_completion_tokens' => 16, ) ), 'timeout' => $timeout, ) ); } /** * Looks a model up without generating anything (used for image models). * * @return array|WP_Error Raw wp_remote_get() result. */ private static function probe_model_availability( $provider, $api_key, $model, $timeout ) { if ( 'google' === $provider ) { return wp_remote_get( 'https://generativelanguage.googleapis.com/v1beta/models/' . $model, array( //phpcs:ignore PluginCheck.CodeAnalysis.AIProvider.DirectIntegration 'headers' => array( 'x-goog-api-key' => $api_key ), 'timeout' => $timeout, ) ); } return wp_remote_get( 'https://api.openai.com/v1/models/' . rawurlencode( $model ), array( //phpcs:ignore PluginCheck.CodeAnalysis.AIProvider.DirectIntegration 'headers' => array( 'Authorization' => 'Bearer ' . $api_key ), 'timeout' => $timeout, ) ); } /** * Settings page field where the model for a feature is chosen, as an * in-page anchor. Defaults to the main model table. * * @param string|false $feature * @return string */ private static function get_model_field_anchor( $feature ) { if ( 'chatbot' === $feature ) { return '#wtofe_chatbot_model'; } if ( is_string( $feature ) && '' !== $feature ) { return '#wtofe_ai_model_' . $feature; } return '#wtofe_ai_model_title'; } /** * @return array{label: string, url: string, external: bool} */ private static function fix_link( $label, $url, $external = false ) { return array( 'label' => $label, 'url' => $url, 'external' => $external, ); } /** * @param string $provider * @return string */ private static function get_provider_label( $provider ) { $labels = array( 'openai' => 'OpenAI', 'anthropic' => 'Anthropic', 'google' => 'Google Gemini', ); return $labels[ $provider ] ?? ucfirst( (string) $provider ); } /** * Provider dashboard pages each error category links to. * * @param string $provider * @return array{keys: string, billing: string, limits: string, models: string, status: string} */ private static function get_provider_fix_urls( $provider ) { $urls = array( 'openai' => array( 'keys' => 'https://platform.openai.com/api-keys', 'billing' => 'https://platform.openai.com/settings/organization/billing/overview', 'limits' => 'https://platform.openai.com/settings/organization/limits', 'models' => 'https://developers.openai.com/api/docs/models', 'status' => 'https://status.openai.com/', ), 'anthropic' => array( 'keys' => 'https://platform.claude.com/settings/keys', 'billing' => 'https://platform.claude.com/settings/billing', 'limits' => 'https://platform.claude.com/settings/limits', 'models' => 'https://platform.claude.com/docs/en/models/overview', 'status' => 'https://status.claude.com/', ), 'google' => array( 'keys' => 'https://aistudio.google.com/app/apikey', 'billing' => 'https://ai.google.dev/gemini-api/docs/billing', 'limits' => 'https://aistudio.google.com/usage', 'models' => 'https://ai.google.dev/gemini-api/docs/models', 'status' => 'https://aistudio.google.com/status', ), ); return $urls[ $provider ] ?? $urls['openai']; } }