settings = $settings;
// Get the post ID from the URL
$post_id = isset($_GET['post']) ? intval($_GET['post']) : 0;
if (!empty($_GET['post_type'])) {
$post_type = $_GET['post_type'];
} else if ($post_id > 0) {
$post_type = get_post_type($post_id);
} else {
$post_type = '';
}
if (!empty($this->isEnabledWriteWithAI()) && $post_type == 'docs') {
add_action('admin_footer', [$this, 'ai_autowrite_button']);
}
add_action('wp_ajax_generate_openai_content', [$this, 'generate_openai_content_callback']);
}
public function isEnabledWriteWithAI()
{
$isEnableAutoWrite = $this->settings->get('enable_write_with_ai', true);
return $isEnableAutoWrite;
}
public function isValidAPIKey($apiKey)
{
if (empty($apiKey)) {
$api_response['valid'] = false;
$api_response['message'] = 'Please Insert your OpenAI API Key to use this Write with AI feature.';
return $api_response;
}
$ch = curl_init('https://api.openai.com/v1/engines');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey,
]);
$api_response = [];
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
$api_response['valid'] = true;
$api_response['message'] = 'Valid API Key';
} else {
$responseData = json_decode($response, true);
// Access the message data (replace 'data' with the actual key used in the response)
$messageData = $responseData['error'] ? $responseData['error'] : '';
$api_response['valid'] = false;
$api_response['message'] = $messageData['message'] ? $messageData['message'] : 'Invalid API Key';
}
// print_r($response);
return $api_response;
}
public function get_api_key()
{
$api_key = $this->settings->get('ai_autowrite_api_key', '');
return $api_key;
}
public function generate_openai_response($prompt, $keywords)
{
try {
$api_key = $this->settings->get('ai_autowrite_api_key', '');
$max_tokens = $this->settings->get('ai_autowrite_max_token', 1500);
$api_endpoint = 'https://api.openai.com/v1/chat/completions'; // Update the endpoint based on OpenAI API version
$request_options = array(
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key,
),
'body' => json_encode(array(
'model' => 'gpt-4o-mini', // Add the model parameter here
'messages' => array(
array('role' => 'system', 'content' => 'You are a helpful assistant who writes documentation for users.'),
array('role' => 'user', 'content' => $prompt),
),
'max_tokens' => $max_tokens,
)),
'timeout' => 50,
);
$response = wp_remote_post($api_endpoint, $request_options);
if (is_wp_error($response)) {
return 'Error: ' . $response->get_error_message();
} else {
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (!empty($data['error'])) {
return $data['error']['message'];
}
return $data['choices'][0]['message']['content']; // Update this line to get the assistant's message
}
} catch (Exception $error) {
return 'Error: ' . $error->getMessage();
}
}
public function generate_openai_content_callback()
{
// Verify the nonce
if (!isset($_POST['ai_nonce']) || !wp_verify_nonce($_POST['ai_nonce'], 'generate_openai_content_nonce')) {
wp_send_json_error('Invalid nonce');
wp_die();
}
$prompt = sanitize_text_field($_POST['prompt']);
// $num_of_sections = sanitize_text_field($_POST['numOfSections']);
// $num_of_paragraphs = sanitize_text_field($_POST['numOfParagraphs']);
$keywords = sanitize_text_field($_POST['keywords']);
$ai_instance = new WriteWithAI($this->settings);
$generated_content = $ai_instance->generate_openai_response($prompt, $keywords);
// Send the generated content as the AJAX response
wp_send_json_success($generated_content);
wp_die();
}
public function ai_autowrite_button()
{
?>