__('Please enter the API key', 'ai-product-assistant') )); } // Get models based on provider $models = $this->get_api_models($provider, $api_key, $api_url); if (is_wp_error($models)) { wp_send_json_error(array( 'message' => $models->get_error_message() )); } else { wp_send_json_success(array( 'models' => $models, 'message' => __('Models retrieved successfully', 'ai-product-assistant') )); } } /** * Get API models from provider * * @param string $provider The API provider * @param string $api_key The API key * @param string $api_url Optional custom API URL * @return array|WP_Error Array of models on success, WP_Error on failure */ private function get_api_models($provider, $api_key, $api_url = '') { switch ($provider) { case 'openai': return $this->get_openai_models($api_key, $api_url); case 'claude': return $this->get_claude_models($api_key, $api_url); case 'gemini': return $this->get_gemini_models($api_key, $api_url); case 'deepseek': return $this->get_deepseek_models($api_key, $api_url); case 'custom': return $this->get_custom_models($api_key, $api_url); default: return new WP_Error('invalid_provider', __('Invalid API Provider', 'ai-product-assistant')); } } /** * Get models from a custom / self-hosted OpenAI-compatible endpoint */ private function get_custom_models($api_key, $api_url = '') { $fallback = array(array('value' => 'custom', 'text' => 'Custom Model')); if (empty($api_url)) { return $fallback; } // Derive /models URL from the completions URL $base_url = rtrim(preg_replace('/\/(chat\/completions|completions)$/', '', rtrim($api_url, '/')), '/'); $models_url = $base_url . '/models'; $headers = array('Content-Type' => 'application/json'); if (!empty($api_key)) { $headers['Authorization'] = 'Bearer ' . $api_key; } $response = wp_remote_get($models_url, array('headers' => $headers, 'timeout' => 15)); if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) { return $fallback; } $body = json_decode(wp_remote_retrieve_body($response), true); if (empty($body['data']) || !is_array($body['data'])) { return $fallback; } $models = array(); foreach ($body['data'] as $model) { if (!empty($model['id'])) { $models[] = array('value' => $model['id'], 'text' => $model['id']); } } return !empty($models) ? $models : $fallback; } /** * Get OpenAI models */ private function get_openai_models($api_key, $api_url = '') { // Always use the standard OpenAI models endpoint $url = 'https://api.openai.com/v1/models'; $response = wp_remote_get( $url, array( 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ), 'timeout' => 15, ) ); if (is_wp_error($response)) { return $response; } $response_code = wp_remote_retrieve_response_code($response); if ($response_code !== 200) { $response_body = json_decode(wp_remote_retrieve_body($response), true); $error_message = isset($response_body['error']['message']) ? $response_body['error']['message'] : __('Failed to retrieve OpenAI models', 'ai-product-assistant'); return new WP_Error('openai_api_error', $error_message); } $response_body = json_decode(wp_remote_retrieve_body($response), true); if (!isset($response_body['data']) || !is_array($response_body['data'])) { return new WP_Error('invalid_response', __('Invalid response format from OpenAI API', 'ai-product-assistant')); } $models = array(); // Exclude non-chat models (embeddings, audio, image, video, moderation, legacy, realtime, research) $exclude_prefixes = array( 'text-embedding', 'text-moderation', 'omni-moderation', 'whisper', 'tts', 'dall-e', 'babbage', 'davinci', 'canary-', 'codex-', 'gpt-5.3-codex', 'sora', 'gpt-image', 'gpt-audio', 'gpt-realtime', 'o1-pro', 'o3-pro', 'o3-deep-research', 'o4-mini-deep-research', 'chatgpt-4o-latest', ); foreach ($response_body['data'] as $model) { if (isset($model['id'])) { $excluded = false; foreach ($exclude_prefixes as $prefix) { if (strpos($model['id'], $prefix) === 0) { $excluded = true; break; } } if (!$excluded) { $models[] = array( 'value' => $model['id'], 'text' => $model['id'] ); } } } // Add custom option $models[] = array( 'value' => 'custom', 'text' => 'Custom Model' ); // Sort models by name usort($models, function($a, $b) { return strcmp($a['text'], $b['text']); }); return $models; } /** * Get Claude models dynamically from API */ private function get_claude_models($api_key, $api_url = '') { if (empty($api_key)) { return new WP_Error('missing_api_key', __('API key is required to retrieve Claude models', 'ai-product-assistant')); } // Always use the standard Claude models endpoint $url = 'https://api.anthropic.com/v1/models'; $response = wp_remote_get( $url, array( 'headers' => array( 'x-api-key' => $api_key, 'anthropic-version' => '2023-06-01', 'Content-Type' => 'application/json' ), 'timeout' => 10, ) ); if (is_wp_error($response)) { return $response; } $response_code = wp_remote_retrieve_response_code($response); if ($response_code !== 200) { $response_body = json_decode(wp_remote_retrieve_body($response), true); $error_message = isset($response_body['error']['message']) ? $response_body['error']['message'] : __('Failed to retrieve Claude models', 'ai-product-assistant'); return new WP_Error('claude_api_error', $error_message); } $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); if (!isset($data['data']) || !is_array($data['data'])) { return new WP_Error('invalid_response', __('Invalid response format from Claude API', 'ai-product-assistant')); } $models = array(); foreach ($data['data'] as $model) { if (isset($model['id']) && isset($model['display_name'])) { $models[] = array( 'value' => $model['id'], 'text' => $model['display_name'] ); } } // Always add custom model option $models[] = array('value' => 'custom', 'text' => 'Custom Model'); // Sort models by text usort($models, function($a, $b) { if ($a['value'] === 'custom') return 1; if ($b['value'] === 'custom') return -1; return strcmp($a['text'], $b['text']); }); return $models; } /** * Get Gemini models dynamically from API */ private function get_gemini_models($api_key, $api_url = '') { if (empty($api_key)) { return new WP_Error('missing_api_key', __('API key is required to retrieve Gemini models', 'ai-product-assistant')); } // Always use the standard Gemini models endpoint with API key $url = 'https://generativelanguage.googleapis.com/v1/models?key=' . $api_key; $response = wp_remote_get( $url, array( 'headers' => array( 'Content-Type' => 'application/json' ), 'timeout' => 10, ) ); if (is_wp_error($response)) { return $response; } $response_code = wp_remote_retrieve_response_code($response); if ($response_code !== 200) { $response_body = json_decode(wp_remote_retrieve_body($response), true); $error_message = isset($response_body['error']['message']) ? $response_body['error']['message'] : __('Failed to retrieve Gemini models', 'ai-product-assistant'); return new WP_Error('gemini_api_error', $error_message); } $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); if (!isset($data['models']) || !is_array($data['models'])) { return new WP_Error('invalid_response', __('Invalid response format from Gemini API', 'ai-product-assistant')); } $models = array(); foreach ($data['models'] as $model) { if (isset($model['name']) && isset($model['displayName'])) { // Extract model ID from the name (e.g., "models/gemini-pro" -> "gemini-pro") $model_id = str_replace('models/', '', $model['name']); // Filter to only show generative models if (strpos($model_id, 'gemini') === 0) { $models[] = array( 'value' => $model_id, 'text' => $model['displayName'] ); } } } // Always add custom model option $models[] = array('value' => 'custom', 'text' => 'Custom Model'); // Sort models by text usort($models, function($a, $b) { if ($a['value'] === 'custom') return 1; if ($b['value'] === 'custom') return -1; return strcmp($a['text'], $b['text']); }); return $models; } /** * Get DeepSeek models dynamically from API */ private function get_deepseek_models($api_key, $api_url = '') { if (empty($api_key)) { return new WP_Error('missing_api_key', __('API key is required to retrieve DeepSeek models', 'ai-product-assistant')); } // Always use the standard DeepSeek models endpoint $url = 'https://api.deepseek.com/models'; $response = wp_remote_get( $url, array( 'headers' => array( 'Accept' => 'application/json', 'Authorization' => 'Bearer ' . $api_key ), 'timeout' => 10, ) ); if (is_wp_error($response)) { return $response; } $response_code = wp_remote_retrieve_response_code($response); if ($response_code !== 200) { $response_body = json_decode(wp_remote_retrieve_body($response), true); $error_message = isset($response_body['error']['message']) ? $response_body['error']['message'] : __('Failed to retrieve DeepSeek models', 'ai-product-assistant'); return new WP_Error('deepseek_api_error', $error_message); } $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); if (!isset($data['data']) || !is_array($data['data'])) { return new WP_Error('invalid_response', __('Invalid response format from DeepSeek API', 'ai-product-assistant')); } $models = array(); foreach ($data['data'] as $model) { if (isset($model['id'])) { // Create a more user-friendly display name $display_name = ucwords(str_replace('-', ' ', $model['id'])); $models[] = array( 'value' => $model['id'], 'text' => $display_name ); } } // Always add custom model option $models[] = array('value' => 'custom', 'text' => 'Custom Model'); // Sort models by text usort($models, function($a, $b) { if ($a['value'] === 'custom') return 1; if ($b['value'] === 'custom') return -1; return strcmp($a['text'], $b['text']); }); return $models; } /** * Handle AJAX request to test API model connection */ public function ajax_test_model_connection() { // Check nonce for security check_ajax_referer('aipa_admin_nonce', 'nonce'); if (!current_user_can('manage_options')) { wp_send_json_error('Insufficient permissions.'); return; } // Get request parameters $provider = isset($_POST['provider']) ? sanitize_text_field(wp_unslash($_POST['provider'])) : ''; $api_key = isset($_POST['api_key']) ? sanitize_text_field(wp_unslash($_POST['api_key'])) : ''; $api_url = isset($_POST['api_url']) ? sanitize_text_field(wp_unslash($_POST['api_url'])) : ''; $api_model = isset($_POST['api_model']) ? sanitize_text_field(wp_unslash($_POST['api_model'])) : ''; $format_template = isset($_POST['format_template']) ? sanitize_text_field(wp_unslash($_POST['format_template'])) : 'openai'; if (empty($api_key) && $provider !== 'custom') { wp_send_json_error(array( 'message' => __('Please enter the API key', 'ai-product-assistant') )); } if ($provider === 'custom' && empty($api_url)) { wp_send_json_error(array( 'message' => __('Please enter the API endpoint URL (e.g. http://localhost:11434/v1/chat/completions)', 'ai-product-assistant') )); return; } if (empty($api_model)) { wp_send_json_error(array( 'message' => __('Please select or enter a model name', 'ai-product-assistant') )); } // Test the API model connection $result = $this->test_model_connection($provider, $api_key, $api_url, $api_model, $format_template); if (is_wp_error($result)) { $error_msg = $result->get_error_message(); // For custom provider, replace OpenAI-specific error messages with a generic one if ($provider === 'custom' && strpos($error_msg, 'platform.openai.com') !== false) { $error_msg = __('Model test failed. Please check the endpoint URL, model name, and that the server is running.', 'ai-product-assistant'); } wp_send_json_error(array('message' => $error_msg)); } else { wp_send_json_success(array( 'message' => __('Model connection successful! The model is valid and accessible.', 'ai-product-assistant') )); } } /** * Test API model connection * * @param string $provider The API provider * @param string $api_key The API key to test * @param string $api_url Optional custom API URL * @param string $api_model The API model to test * @param string $format_template Format template for custom providers * @return true|WP_Error True on success, WP_Error on failure */ private function test_model_connection($provider, $api_key, $api_url = '', $api_model = '', $format_template = 'openai') { switch ($provider) { case 'openai': return $this->test_openai_model($api_key, $api_url, $api_model); case 'claude': return $this->test_claude_model($api_key, $api_url, $api_model); case 'gemini': return $this->test_gemini_model($api_key, $api_url, $api_model); case 'deepseek': return $this->test_deepseek_model($api_key, $api_url, $api_model); case 'custom': // For custom providers, test based on format template switch ($format_template) { case 'openai': case 'deepseek': return $this->test_openai_model($api_key, $api_url, $api_model); case 'claude': return $this->test_claude_model($api_key, $api_url, $api_model); case 'gemini': return $this->test_gemini_model($api_key, $api_url, $api_model); default: return new WP_Error('invalid_format', __('Invalid format template', 'ai-product-assistant')); } default: return new WP_Error('invalid_provider', __('Invalid API Provider', 'ai-product-assistant')); } } /** * Test OpenAI model */ private function test_openai_model($api_key, $api_url = '', $api_model = '') { // Use the API URL from settings if provided, otherwise use default $url = !empty($api_url) ? $api_url : 'https://api.openai.com/v1/chat/completions'; $headers = array( 'Content-Type' => 'application/json', ); if (!empty($api_key)) { $headers['Authorization'] = 'Bearer ' . $api_key; } $body = json_encode(array( 'model' => $api_model, 'messages' => array( array( 'role' => 'system', 'content' => 'You are a helpful assistant.' ), array( 'role' => 'user', 'content' => 'Hello, this is a test message. Please respond with a short acknowledgment.' ) ), 'max_tokens' => 10 )); $response = wp_remote_post( $url, array( 'headers' => $headers, 'body' => $body, 'timeout' => 15, ) ); if (is_wp_error($response)) { return $response; } $response_code = wp_remote_retrieve_response_code($response); if ($response_code !== 200) { $response_body = json_decode(wp_remote_retrieve_body($response), true); $error_message = isset($response_body['error']['message']) ? $response_body['error']['message'] : __('OpenAI Model Connection Failed', 'ai-product-assistant'); return new WP_Error('openai_api_error', $error_message); } return true; } /** * Test Claude model */ private function test_claude_model($api_key, $api_url = '', $api_model = '') { $url = !empty($api_url) ? $api_url : 'https://api.anthropic.com/v1/messages'; $headers = array( 'x-api-key' => $api_key, 'anthropic-version' => '2023-06-01', 'Content-Type' => 'application/json', ); $body = json_encode(array( 'model' => $api_model, 'max_tokens' => 10, 'messages' => array( array( 'role' => 'user', 'content' => 'Hello, this is a test message. Please respond with a short acknowledgment.' ) ) )); $response = wp_remote_post( $url, array( 'headers' => $headers, 'body' => $body, 'timeout' => 15, ) ); if (is_wp_error($response)) { return $response; } $response_code = wp_remote_retrieve_response_code($response); if ($response_code !== 200) { $response_body = json_decode(wp_remote_retrieve_body($response), true); $error_message = isset($response_body['error']['message']) ? $response_body['error']['message'] : __('Claude Model Connection Failed', 'ai-product-assistant'); return new WP_Error('claude_api_error', $error_message); } return true; } /** * Test Gemini model */ private function test_gemini_model($api_key, $api_url = '', $api_model = '') { // Always use the correct Gemini API format for model testing // Ignore the user-configured URL as it's meant for chat completions $api_url = 'https://generativelanguage.googleapis.com/v1/models/' . $api_model . ':generateContent?key=' . $api_key; $headers = array( 'Content-Type' => 'application/json', ); $body = json_encode(array( 'contents' => array( array( 'role' => 'user', 'parts' => array( array( 'text' => 'Hello, this is a test message. Please respond with a short acknowledgment.' ) ) ) ), 'generationConfig' => array( 'maxOutputTokens' => 10 ) )); $response = wp_remote_post( $api_url, array( 'headers' => $headers, 'body' => $body, 'timeout' => 15, ) ); if (is_wp_error($response)) { return $response; } $response_code = wp_remote_retrieve_response_code($response); if ($response_code !== 200) { $response_body = json_decode(wp_remote_retrieve_body($response), true); $error_message = isset($response_body['error']['message']) ? $response_body['error']['message'] : __('Gemini Model Connection Failed', 'ai-product-assistant'); return new WP_Error('gemini_api_error', $error_message); } return true; } /** * Test DeepSeek model */ private function test_deepseek_model($api_key, $api_url = '', $api_model = '') { // DeepSeek API is compatible with OpenAI, so we can reuse the same function return $this->test_openai_model($api_key, $api_url, $api_model); } /** * Handle AJAX request to test API connection */ public function ajax_test_api_connection() { // Check nonce for security check_ajax_referer('aipa_admin_nonce', 'nonce'); if (!current_user_can('manage_options')) { wp_send_json_error('Insufficient permissions.'); return; } // Get request parameters $provider = isset($_POST['provider']) ? sanitize_text_field(wp_unslash($_POST['provider'])) : ''; $api_key = isset($_POST['api_key']) ? sanitize_text_field(wp_unslash($_POST['api_key'])) : ''; $api_url = isset($_POST['api_url']) ? sanitize_text_field(wp_unslash($_POST['api_url'])) : ''; $api_model = isset($_POST['api_model']) ? sanitize_text_field(wp_unslash($_POST['api_model'])) : ''; $format_template = isset($_POST['format_template']) ? sanitize_text_field(wp_unslash($_POST['format_template'])) : 'openai'; if (empty($api_key) && $provider !== 'custom') { wp_send_json_error(array( 'message' => __('Please enter the API key', 'ai-product-assistant') )); } if ($provider === 'custom' && empty($api_url)) { wp_send_json_error(array( 'message' => __('Please enter the API endpoint URL (e.g. http://localhost:11434/v1/chat/completions)', 'ai-product-assistant') )); return; } // Test the API connection based on the provider $result = $this->test_api_connection($provider, $api_key, $api_url, $api_model, $format_template); if (is_wp_error($result)) { wp_send_json_error(array( 'message' => $result->get_error_message() )); } else { wp_send_json_success(array( 'message' => __('API Connection Success', 'ai-product-assistant') )); } } /** * Test API connection with provided credentials * * @param string $provider The API provider * @param string $api_key The API key to test * @param string $api_url Optional custom API URL * @param string $api_model Optional custom API model * @param string $format_template Format template for custom providers * @return true|WP_Error True on success, WP_Error on failure */ private function test_api_connection($provider, $api_key, $api_url = '', $api_model = '', $format_template = 'openai') { switch ($provider) { case 'openai': return $this->test_openai_connection($api_key, $api_url); case 'claude': return $this->test_claude_connection($api_key, $api_url); case 'gemini': return $this->test_gemini_connection($api_key, $api_url); case 'deepseek': return $this->test_deepseek_connection($api_key, $api_url); case 'custom': return $this->test_custom_connection($api_key, $api_url); default: return new WP_Error('invalid_provider', __('Invalid API Provider', 'ai-product-assistant')); } } /** * Test custom / self-hosted LLM connection via the OpenAI-compatible /models endpoint */ private function test_custom_connection($api_key, $api_url) { if (empty($api_url)) { return new WP_Error('missing_url', __('Please enter the API endpoint URL for your self-hosted LLM (e.g. http://localhost:11434/v1/chat/completions).', 'ai-product-assistant')); } // Derive the /models listing URL: strip /chat/completions or /completions suffix $base_url = rtrim(preg_replace('/\/(chat\/completions|completions)$/', '', rtrim($api_url, '/')), '/'); $models_url = $base_url . '/models'; $headers = array('Content-Type' => 'application/json'); if (!empty($api_key)) { $headers['Authorization'] = 'Bearer ' . $api_key; } $response = wp_remote_get($models_url, array('headers' => $headers, 'timeout' => 15)); if (is_wp_error($response)) { return new WP_Error('connection_failed', sprintf( /* translators: %s: server base URL */ __('Could not connect to %s. Make sure your LLM server is running and accessible from this WordPress server.', 'ai-product-assistant'), esc_url($base_url) ) ); } $response_code = wp_remote_retrieve_response_code($response); if ($response_code !== 200) { return new WP_Error('connection_error', sprintf( /* translators: 1: server base URL, 2: HTTP status code */ __('Server at %1$s returned HTTP %2$d. Please verify the endpoint URL and server configuration.', 'ai-product-assistant'), esc_url($base_url), $response_code ) ); } return true; } /** * Test OpenAI API connection */ private function test_openai_connection($api_key, $api_url = '') { // Always use the standard OpenAI models endpoint for connection test $url = 'https://api.openai.com/v1/models'; $response = wp_remote_get( $url, array( 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ), 'timeout' => 15, ) ); if (is_wp_error($response)) { return $response; } $response_code = wp_remote_retrieve_response_code($response); if ($response_code !== 200) { $response_body = json_decode(wp_remote_retrieve_body($response), true); $error_message = isset($response_body['error']['message']) ? $response_body['error']['message'] : __('OpenAI API Connection Failed', 'ai-product-assistant'); return new WP_Error('openai_api_error', $error_message); } return true; } /** * Test Claude API connection */ private function test_claude_connection($api_key, $api_url = '') { // Use the API URL from settings if provided, otherwise use default $url = !empty($api_url) ? $api_url : 'https://api.anthropic.com/v1/messages'; $headers = array( 'x-api-key' => $api_key, 'anthropic-version' => '2023-06-01', 'Content-Type' => 'application/json', ); $body = json_encode(array( 'model' => 'claude-haiku-4-5-20251001', 'max_tokens' => 10, 'messages' => array( array( 'role' => 'user', 'content' => 'Hello' ) ) )); $response = wp_remote_post( $url, array( 'headers' => $headers, 'body' => $body, 'timeout' => 15, ) ); if (is_wp_error($response)) { return $response; } $response_code = wp_remote_retrieve_response_code($response); if ($response_code !== 200) { $response_body = json_decode(wp_remote_retrieve_body($response), true); $error_message = isset($response_body['error']['message']) ? $response_body['error']['message'] : __('Claude API Connection Failed', 'ai-product-assistant'); return new WP_Error('claude_api_error', $error_message); } return true; } /** * Test Gemini API connection */ private function test_gemini_connection($api_key, $api_url = '') { // Always use the standard Gemini models endpoint for connection test $api_url = 'https://generativelanguage.googleapis.com/v1/models?key=' . $api_key; $response = wp_remote_get( $api_url, array( 'timeout' => 15, ) ); if (is_wp_error($response)) { return $response; } $response_code = wp_remote_retrieve_response_code($response); if ($response_code !== 200) { $response_body = json_decode(wp_remote_retrieve_body($response), true); $error_message = isset($response_body['error']['message']) ? $response_body['error']['message'] : __('Gemini API Connection Failed', 'ai-product-assistant'); return new WP_Error('gemini_api_error', $error_message); } return true; } /** * Test DeepSeek API connection (similar to OpenAI) */ private function test_deepseek_connection($api_key, $api_url = '') { // Always use the standard DeepSeek models endpoint for connection test $url = 'https://api.deepseek.com/v1/models'; $response = wp_remote_get( $url, array( 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ), 'timeout' => 15, ) ); if (is_wp_error($response)) { return $response; } $response_code = wp_remote_retrieve_response_code($response); if ($response_code !== 200) { $response_body = json_decode(wp_remote_retrieve_body($response), true); $error_message = isset($response_body['error']['message']) ? $response_body['error']['message'] : __('DeepSeek API Connection Failed', 'ai-product-assistant'); return new WP_Error('deepseek_api_error', $error_message); } return true; } /** * API Section callback */ public function api_section_callback() { echo '

' . esc_html(__('Configure your AI API settings by following these steps:', 'ai-product-assistant')) . '

'; } /** * API Provider callback */ public function api_provider_callback() { $options = get_option('aipa_settings'); $provider = isset($options['api_provider']) ? $options['api_provider'] : 'openai'; ?>

1

2

4

Lower-tier models (e.g., GPT-3.5, Claude Haiku, Gemini Flash): Less accurate search results and reduced customer experience, but lower API costs.', 'ai-product-assistant'), array('strong' => array())); ?>

Higher-tier models (e.g., GPT-4, Claude Opus, Gemini Pro): More precise matching and better customer experience, but higher API costs.', 'ai-product-assistant'), array('strong' => array())); ?>

3