'Claude (Anthropic)', 'openai' => 'ChatGPT (OpenAI)', 'gemini' => 'Gemini (Google)' ); /** * Available models for each provider. */ const MODELS = array( 'claude' => array( 'claude-3-haiku-20240307' => 'Claude 3 Haiku', 'claude-3-5-haiku-20241022' => 'Claude 3.5 Haiku', 'claude-3-5-sonnet-20241022' => 'Claude 3.5 Sonnet', 'claude-sonnet-4-20250514' => 'Claude Sonnet 4' ), 'openai' => array( 'gpt-4o' => 'GPT-4o', 'gpt-4o-mini' => 'GPT-4o Mini', 'gpt-4.1-2025-04-14' => 'GPT-4.1', 'gpt-4.1-mini-2025-04-14' => 'GPT-4.1 Mini' ), 'gemini' => array( 'gemini-1.5-pro' => 'Gemini 1.5 Pro', 'gemini-1.5-flash' => 'Gemini 1.5 Flash', 'gemini-2.5-flash' => 'Gemini 2.5 Flash', 'gemini-2.5-pro' => 'Gemini 2.5 Pro' ) ); /** * API endpoints for each provider. */ private $api_endpoints = array( 'claude' => 'https://api.anthropic.com/v1/messages', 'openai' => 'https://api.openai.com/v1/chat/completions', 'gemini' => 'https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent' ); /** * Plugin options. * * @var array */ private $options; /** * Constructor. */ public function __construct() { $this->options = get_option('ai_smart_excerpt_options', array()); } /** * Generate excerpt using the configured LLM provider. * * @param string $content Post content. * @param string $title Post title. * @param string $excerpt_type Type of excerpt (seo, social, summary, teaser). * @param int $max_length Maximum excerpt length. * @return string|false Generated excerpt or false on failure. */ public function generate_excerpt($content, $title, $excerpt_type = 'seo', $max_length = 300) { $provider = $this->options['llm_provider'] ?? 'claude'; $api_key = $this->options['api_key'] ?? ''; if (empty($api_key)) { return false; } if (empty($content)) { return false; } $prompt = $this->build_prompt($content, $title, $excerpt_type, $max_length); switch ($provider) { case 'claude': return $this->call_claude_api($prompt, $api_key); case 'openai': return $this->call_openai_api($prompt, $api_key); case 'gemini': return $this->call_gemini_api($prompt, $api_key); default: return false; } } /** * Build the prompt for AI generation. * * @param string $content Post content. * @param string $title Post title. * @param string $excerpt_type Type of excerpt. * @param int $max_length Maximum length. * @return string Generated prompt. */ private function build_prompt($content, $title, $excerpt_type, $max_length) { $type_instructions = array( 'seo' => 'Create an SEO-optimized excerpt that includes relevant keywords and is designed to improve search engine rankings. Focus on the main topic and key points that would help with discoverability.', 'social' => 'Create a social media optimized excerpt that is engaging, shareable, and likely to generate clicks and engagement. Make it compelling and attention-grabbing.', 'summary' => 'Create a clear, factual summary of the main points covered in the content. Focus on providing a comprehensive overview of the key information.', 'teaser' => 'Create an engaging teaser that creates curiosity and encourages readers to read the full content. Make it intriguing while providing just enough information to hook the reader.' ); $instruction = $type_instructions[$excerpt_type] ?? $type_instructions['summary']; $prompt = sprintf( 'Please create a %s excerpt for the following article. Title: %s Content: %s Requirements: - %s - Maximum length: %d characters - Write in a natural, readable style - Focus on the most important and relevant information - Do not include quotes, markdown, or special formatting - Return only the excerpt text, nothing else Excerpt:', $excerpt_type, $title, $content, $instruction, $max_length ); return $prompt; } /** * Call Claude API. * * @param string $prompt The prompt. * @param string $api_key API key. * @return string|false Generated excerpt or false. */ private function call_claude_api($prompt, $api_key) { $headers = array( 'Content-Type' => 'application/json', 'x-api-key' => $api_key, 'anthropic-version' => '2023-06-01' ); $body = array( 'model' => $this->get_selected_model('claude'), 'max_tokens' => 300, 'messages' => array( array( 'role' => 'user', 'content' => $prompt ) ) ); $response = wp_remote_post($this->api_endpoints['claude'], array( 'headers' => $headers, 'body' => wp_json_encode($body), 'timeout' => 30 )); return $this->parse_claude_response($response); } /** * Call OpenAI API. * * @param string $prompt The prompt. * @param string $api_key API key. * @return string|false Generated excerpt or false. */ private function call_openai_api($prompt, $api_key) { $headers = array( 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_key ); $body = array( 'model' => $this->get_selected_model('openai'), 'messages' => array( array( 'role' => 'user', 'content' => $prompt ) ), 'max_tokens' => 300, 'temperature' => 0.7 ); $response = wp_remote_post($this->api_endpoints['openai'], array( 'headers' => $headers, 'body' => wp_json_encode($body), 'timeout' => 30 )); return $this->parse_openai_response($response); } /** * Call Gemini API. * * @param string $prompt The prompt. * @param string $api_key API key. * @return string|false Generated excerpt or false. */ private function call_gemini_api($prompt, $api_key) { $model = $this->get_selected_model('gemini'); $url = str_replace('{model}', $model, $this->api_endpoints['gemini']) . '?key=' . $api_key; $headers = array( 'Content-Type' => 'application/json' ); $body = array( 'contents' => array( array( 'parts' => array( array('text' => $prompt) ) ) ), 'generationConfig' => array( 'maxOutputTokens' => 300, 'temperature' => 0.7 ) ); $response = wp_remote_post($url, array( 'headers' => $headers, 'body' => wp_json_encode($body), 'timeout' => 30 )); return $this->parse_gemini_response($response); } /** * Parse Claude API response. * * @param array|WP_Error $response API response. * @return string|false Parsed excerpt or false. */ private function parse_claude_response($response) { if (is_wp_error($response)) { return false; } $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); if (!$data || !isset($data['content'][0]['text'])) { return false; } return trim($data['content'][0]['text']); } /** * Parse OpenAI API response. * * @param array|WP_Error $response API response. * @return string|false Parsed excerpt or false. */ private function parse_openai_response($response) { if (is_wp_error($response)) { return false; } $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); if (!$data || !isset($data['choices'][0]['message']['content'])) { return false; } return trim($data['choices'][0]['message']['content']); } /** * Parse Gemini API response. * * @param array|WP_Error $response API response. * @return string|false Parsed excerpt or false. */ private function parse_gemini_response($response) { if (is_wp_error($response)) { return false; } $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); if (!$data || !isset($data['candidates'][0]['content']['parts'][0]['text'])) { return false; } return trim($data['candidates'][0]['content']['parts'][0]['text']); } /** * Test API connection. * * @param string $provider Provider to test. * @param string $api_key API key to test. * @return array Test result with success status and message. */ public function test_api_connection($provider, $api_key) { $test_prompt = 'Write a brief test response to confirm the API connection is working.'; // Temporarily set the provider and key for testing $original_provider = $this->options['llm_provider']; $original_key = $this->options['api_key']; $this->options['llm_provider'] = $provider; $this->options['api_key'] = $api_key; $result = $this->generate_excerpt( 'This is a test article to verify API connectivity.', 'Test Article', 'general', 100 ); // Restore original settings $this->options['llm_provider'] = $original_provider; $this->options['api_key'] = $original_key; if ($result) { return array( 'success' => true, 'message' => __('API connection successful!', 'ai-smart-excerpt') ); } else { return array( 'success' => false, 'message' => __('API connection failed. Please check your API key and try again.', 'ai-smart-excerpt') ); } } /** * Get supported providers. * * @return array Supported providers. */ public static function get_providers() { return self::PROVIDERS; } /** * Validate API key format. * * @param string $provider Provider name. * @param string $api_key API key to validate. * @return bool True if format is valid. */ public function validate_api_key_format($provider, $api_key) { if (empty($api_key)) { return false; } switch ($provider) { case 'claude': return strpos($api_key, 'sk-ant-') === 0; case 'openai': return strpos($api_key, 'sk-') === 0; case 'gemini': return preg_match('/^[A-Za-z0-9_-]+$/', $api_key); default: return false; } } /** * Get the selected model for a provider. * * @param string $provider Provider name. * @return string Model identifier. */ private function get_selected_model($provider) { $model_option = $provider . '_model'; $selected_model = isset($this->options[$model_option]) ? $this->options[$model_option] : null; // Return selected model if valid, otherwise return default if ($selected_model && isset(self::MODELS[$provider][$selected_model])) { return $selected_model; } // Return first available model as default $models = self::MODELS[$provider]; return array_key_first($models); } /** * Get available models for a provider. * * @param string $provider Provider name. * @return array Available models. */ public static function get_models_for_provider($provider) { return isset(self::MODELS[$provider]) ? self::MODELS[$provider] : array(); } }