esc_html__('API key is missing. Please configure it in the plugin settings.', 'ai-powered-comment-moderator') ]; } // ? If you want to respect the user's chosen model from admin settings: $model = get_option('aicomo_model', 'gpt-4-turbo'); // ? Sanitize input (prevent injection attacks) $comment_text = sanitize_text_field($comment_text); // ? Cache key to reduce redundant API calls $cache_key = 'aicomo_' . md5($comment_text); $cached_result = get_transient($cache_key); if ($cached_result) { return $cached_result; // Return cached response } // ? Build request body for ChatGPT $request_body = json_encode([ 'model' => $model, // replaced 'gpt-4o' with your saved option 'messages' => [ [ 'role' => 'system', // enforce the same format: "Decision: [Yes/No], Confidence: [0-100]" 'content' => 'You are a professional blogger. Determine if the comment makes sense in a logical conversation. Answer "Yes" or "No". Additionally, provide a confidence score between 0-100 based on how logical and coherent the comment is. Format: "Decision: [Yes/No], Confidence: [0-100]"' ], [ 'role' => 'user', 'content' => $comment_text ] ], 'temperature' => 0 ]); // ? WordPress API Request to ChatGPT $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [ 'body' => $request_body, 'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . sanitize_text_field($api_key), ], 'timeout' => 10 ]); // ? Check for WP_Error if (is_wp_error($response)) { return [ 'error' => esc_html__('AI moderation request failed.', 'ai-powered-comment-moderator') ]; } // ? Check for non-200 status codes $http_code = wp_remote_retrieve_response_code($response); if ($http_code !== 200) { return [ 'error' => esc_html__('AI moderation API returned an error.', 'ai-powered-comment-moderator') ]; } // ? Process ChatGPT’s response $body = json_decode(wp_remote_retrieve_body($response), true); $message_content = isset($body['choices'][0]['message']['content']) ? strtolower(trim($body['choices'][0]['message']['content'])) : ''; // ? Extract Decision: yes/no and Confidence: preg_match('/decision:\\s*(yes|no)/i', $message_content, $decision_match); preg_match('/confidence:\\s*(\\d+)/i', $message_content, $confidence_match); $decision = !empty($decision_match[1]) && strtolower($decision_match[1]) === 'yes'; $confidence = !empty($confidence_match[1]) ? intval($confidence_match[1]) : 0; // ? Store result in cache (5 minutes) $result = [ 'decision' => $decision, // boolean 'confidence' => $confidence // integer ]; set_transient($cache_key, $result, 5 * MINUTE_IN_SECONDS); return $result; } }