*/ class A1AI_OpenAI { /** * The data manager instance. * * @since 1.0.0 * @access private * @var A1AI_Data_Manager $data_manager Handles database operations. */ private $data_manager; /** * Initialize the class and set its properties. * * @since 1.0.0 * @param A1AI_Data_Manager $data_manager The data manager instance. */ public function __construct($data_manager = null) { // If data manager wasn't passed, create one if (null === $data_manager) { require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-a1ai-data-manager.php'; $this->data_manager = new A1AI_Data_Manager(); } else { $this->data_manager = $data_manager; } } /** * Process a conversation with OpenAI. * * @since 1.0.0 * @param int $conversation_id The conversation ID. * @param string $message The user message. * @param array $settings The chatbot settings. * @return array The response with success status and message or error. */ public function process_conversation($conversation_id, $message, $settings) { // Get chatbot ID from settings $chatbot_id = isset($settings['chatbot_id']) ? intval($settings['chatbot_id']) : 0; // Check for matching adjustments first if ($chatbot_id > 0) { $adjustments = $this->data_manager->get_adjustments($chatbot_id); if (!empty($adjustments)) { foreach ($adjustments as $adjustment) { // Simple string comparison for now (can be enhanced later) $user_input = trim(strtolower($adjustment['user_input'])); $current_message = trim(strtolower($message)); // Check for exact match or contains match based on match type $is_match = false; switch ($adjustment['ui_match_type']) { case 'Exact': $is_match = ($user_input === $current_message); break; case 'Phrase': $is_match = (strpos($current_message, $user_input) !== false); break; case 'Flexible': case 'Broad': default: // Simple contains check for broad matching $is_match = ( (strpos($current_message, $user_input) !== false) || (strpos($user_input, $current_message) !== false) ); // Only use levenshtein for shorter strings to avoid performance issues if (!$is_match && strlen($current_message) <= 255 && strlen($user_input) <= 255) { $max_length = max(strlen($current_message), strlen($user_input)); if ($max_length > 0) { $similarity = levenshtein($current_message, $user_input) / $max_length; $is_match = $similarity < 0.3; // Less than 30% difference } } break; } // If we have a match, return the adjustment output if ($is_match) { return array( 'success' => true, 'message' => $adjustment['ai_output'], 'tokens_used' => 0, // No tokens used for adjustments 'from_adjustment' => true, ); } } } } // No adjustment matched, proceed with normal OpenAI request // Get message history for this conversation $history = $this->data_manager->get_conversation_messages($conversation_id); // Prepare messages for OpenAI $messages = $this->prepare_messages($history, $message, $settings); // Send request to OpenAI $response = $this->send_request($messages, $settings); // Process response if ($response['success']) { $ai_message = $this->extract_message($response['data']); $token_usage = $this->extract_token_usage($response['data']); return array( 'success' => true, 'message' => $ai_message, 'tokens_used' => $token_usage, ); } else { return array( 'success' => false, 'error' => $response['message'], ); } } /** * Prepare messages for OpenAI API request. * * @since 1.0.0 * @param array $history Previous messages in the conversation. * @param string $message The new user message. * @param array $settings The chatbot settings. * @return array Formatted messages for OpenAI API. */ private function prepare_messages($history, $message, $settings) { $messages = array(); // Get chatbot ID from settings or conversation $chatbot_id = isset($settings['chatbot_id']) ? intval($settings['chatbot_id']) : 0; // Get system prompt from custom instructions table $system_prompt = ''; if ($chatbot_id > 0) { $system_instructions = $this->data_manager->get_custom_instructions($chatbot_id, 'system'); if (!empty($system_instructions) && is_array($system_instructions)) { foreach ($system_instructions as $instruction) { if ($instruction['instruction_name'] === 'System Prompt' && !empty($instruction['instruction_content'])) { $system_prompt = $instruction['instruction_content']; break; } } } } // Get general custom instructions from dedicated table $custom_instructions = ''; if ($chatbot_id > 0) { $instructions_array = $this->data_manager->get_custom_instructions($chatbot_id, 'general'); if (!empty($instructions_array) && is_array($instructions_array)) { $instructions_text = ''; foreach ($instructions_array as $instruction) { if (!empty($instruction['instruction_content'])) { $instructions_text .= $instruction['instruction_content'] . "\n\n"; } } $custom_instructions = trim($instructions_text); } } // Combine system prompt and custom instructions $system_content = ''; if (!empty($system_prompt)) { $system_content .= $system_prompt . "\n\n"; } if (!empty($custom_instructions)) { $system_content .= $custom_instructions; } // Add system message if (!empty($system_content)) { $messages[] = array( 'role' => 'system', 'content' => sanitize_textarea_field($system_content), ); } else { // Default system message $messages[] = array( 'role' => 'system', 'content' => 'You are a helpful assistant on a WordPress website.', ); } // Add initial messages if provided if (!empty($settings['initial_messages']) && is_array($settings['initial_messages'])) { foreach ($settings['initial_messages'] as $initial_message) { if (!empty($initial_message['role']) && !empty($initial_message['content'])) { $messages[] = array( 'role' => sanitize_text_field($initial_message['role']), 'content' => sanitize_textarea_field($initial_message['content']), ); } } } // Add conversation history if (!empty($history) && is_array($history)) { foreach ($history as $msg) { $messages[] = array( 'role' => sanitize_text_field($msg['role']), 'content' => $msg['content'], ); } } // Add current user message $messages[] = array( 'role' => 'user', 'content' => $message, ); return $messages; } /** * Send request to OpenAI API. * * @since 1.0.0 * @param array $messages The formatted messages. * @param array $settings The API settings. * @return array The response with success status and data or error message. */ private function send_request($messages, $settings) { // Get API key from settings $api_key = get_option('a1ai_openai_api_key', ''); if (empty($api_key)) { return array( 'success' => false, 'message' => esc_html__('OpenAI API key is not configured.', 'a1ai-chatbot'), ); } // Default settings $defaults = array( 'model' => 'gpt-4o', 'temperature' => 0.7, 'max_tokens' => 1000, ); // Merge with provided settings $api_settings = wp_parse_args( array( 'model' => isset($settings['model']) ? sanitize_text_field($settings['model']) : $defaults['model'], 'temperature' => isset($settings['temperature']) ? (float) $settings['temperature'] : $defaults['temperature'], 'max_tokens' => isset($settings['max_tokens']) ? (int) $settings['max_tokens'] : $defaults['max_tokens'], ), $defaults ); // Prepare request data $request_data = array( 'model' => $api_settings['model'], 'messages' => $messages, 'temperature' => $api_settings['temperature'], 'max_tokens' => $api_settings['max_tokens'], ); // Prepare HTTP request $args = array( 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ), 'timeout' => 60, 'body' => wp_json_encode($request_data), ); // Send request to OpenAI $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args); // Check for errors if (is_wp_error($response)) { return array( 'success' => false, 'message' => $response->get_error_message(), ); } // Get response code and body $response_code = wp_remote_retrieve_response_code($response); $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); // Check if response is successful if (200 !== $response_code) { $error_message = isset($data['error']['message']) ? sanitize_text_field($data['error']['message']) : esc_html__('Unknown error occurred.', 'a1ai-chatbot'); return array( 'success' => false, 'message' => $error_message, 'code' => $response_code, ); } // Return success with data return array( 'success' => true, 'data' => $data, ); } /** * Extract message from OpenAI response. * * @since 1.0.0 * @param array $data The response data. * @return string The extracted message content. */ private function extract_message($data) { if (isset($data['choices'][0]['message']['content'])) { return $data['choices'][0]['message']['content']; } return esc_html__('No response generated.', 'a1ai-chatbot'); } /** * Extract token usage from OpenAI response. * * @since 1.0.0 * @param array $data The response data. * @return int The total token usage or 0 if not available. */ private function extract_token_usage($data) { if (isset($data['usage']['total_tokens'])) { return (int) $data['usage']['total_tokens']; } return 0; } }