[ 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', 'OpenAI-Beta' => 'assistants=v2' ], 'body' => wp_json_encode(new stdClass()), // Empty body as per OpenAI's documentation for thread creation 'method' => 'POST', 'data_format' => 'body', ]; $response = wp_remote_post($url, $args); if (is_wp_error($response)) { error_log('Thread creation failed: ' . $response->get_error_message()); return null; } $response_body = wp_remote_retrieve_body($response); $response_data = json_decode($response_body, true); if (isset($response_data['error'])) { error_log('OpenAI API Error: ' . $response_data['error']['message']); return null; } $thread_id = $response_data['id'] ?? null; if ($thread_id) { if (function_exists('AI24AI_add_thread_to_db')) { AI24AI_add_thread_to_db($thread_id, $platform); } if (function_exists('AI24AI_store_thread_id_in_session')) { AI24AI_store_thread_id_in_session($thread_id); } return $thread_id; } else { error_log('Failed to get thread ID from response.'); return null; } } //Function to send messages to thread function AI24AI_send_message_to_thread($thread_id, $user_input) { $api_key = get_option('AI24AI_api_key'); // Retrieve API key from WP options $base_api_url = "https://api.openai.com/v1"; $endpoint = "/threads/{$thread_id}/messages"; $url = $base_api_url . $endpoint; $args = [ 'headers' => [ 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', 'OpenAI-Beta' => 'assistants=v2' ], 'body' => wp_json_encode([ 'role' => 'user', 'content' => $user_input ]), 'method' => 'POST', 'data_format' => 'body', ]; $response = wp_remote_post($url, $args); if (is_wp_error($response)) { error_log('Message sending failed: ' . $response->get_error_message()); return null; } $response_body = wp_remote_retrieve_body($response); $response_data = json_decode($response_body, true); if (isset($response_data['error'])) { error_log('OpenAI API Error: ' . $response_data['error']['message']); return null; } // Assuming successful message sending, log the message ID $message_id = $response_data['id'] ?? null; if ($message_id) { return $message_id; } else { error_log('Failed to get message ID from response.'); return null; } } //Function to create a run with designated ASSISTANT ID function AI24AI_create_run($thread_id, $assistant_id) { $api_key = get_option('AI24AI_api_key'); // Retrieve API key from WP options $base_api_url = "https://api.openai.com/v1"; $create_endpoint = "/threads/{$thread_id}/runs"; $create_url = $base_api_url . $create_endpoint; // Create run $create_args = [ 'headers' => [ 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', 'OpenAI-Beta' => 'assistants=v2' ], 'body' => wp_json_encode([ 'assistant_id' => $assistant_id, // Optionally add 'model', 'instructions', 'tools' here if needed ]), 'method' => 'POST', 'data_format' => 'body', ]; $create_response = wp_remote_post($create_url, $create_args); if (is_wp_error($create_response)) { error_log('Run creation failed: ' . $create_response->get_error_message()); return null; } $create_response_body = wp_remote_retrieve_body($create_response); $create_response_data = json_decode($create_response_body, true); if (isset($create_response_data['error'])) { error_log('OpenAI API Error: ' . $create_response_data['error']['message']); return null; } $run_id = $create_response_data['id'] ?? null; if (!$run_id) { error_log('Failed to get run ID from response.'); return null; } // Retrieve run for detailed logging $retrieve_endpoint = "/threads/{$thread_id}/runs/{$run_id}"; $retrieve_url = $base_api_url . $retrieve_endpoint; $retrieve_response = wp_remote_get($retrieve_url, [ 'headers' => [ 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', 'OpenAI-Beta' => 'assistants=v2' ] ]); if (is_wp_error($retrieve_response)) { error_log('Failed to retrieve run details: ' . $retrieve_response->get_error_message()); return $run_id; } $retrieve_response_body = wp_remote_retrieve_body($retrieve_response); $retrieve_response_data = json_decode($retrieve_response_body, true); if (isset($retrieve_response_data['error'])) { error_log('OpenAI API Error on retrieval: ' . $retrieve_response_data['error']['message']); return $run_id; } return $run_id; } function AI24AI_clean_gpt_response($text) { $pattern = '/【\d+(:\d+)?†source】/'; $cleaned_text = preg_replace($pattern, '', $text); return $cleaned_text; } function AI24AI_process_markdown_and_links($message) { $options = get_option('AI24AI_text_options', array('markdown_enabled' => 1)); if (isset($options['markdown_enabled']) && $options['markdown_enabled']) { // Initialize Parsedown only once static $Parsedown = null; if ($Parsedown === null) { $Parsedown = new Parsedown(); } // Convert Markdown to HTML $message = $Parsedown->text($message); } else { // Convert Markdown to plain text, keep links $message = AI24AI_strip_markdown($message); $message = AI24AI_convert_links($message); } return $message; } function AI24AI_strip_markdown($text) { // Strip Markdown syntax to plain text but keep links $text = preg_replace('/(\*\*|__)(.*?)\1/', '\2', $text); // bold $text = preg_replace('/(\*|_)(.*?)\1/', '\2', $text); // italic $text = preg_replace('/\#(.*?)\n/', '\1\n', $text); // headers $text = preg_replace('/\n\-(.*?)\n/', '\1\n', $text); // lists return wp_strip_all_tags($text); // Strip any remaining HTML tags } function AI24AI_convert_links($text) { // Convert Markdown links to HTML links $text = preg_replace('/\[([^\]]+)\]\((http[s]?:\/\/[^\s]+)\)/', '$1', $text); return $text; } // Function to poll for a response, retrieve run steps, and messages if completed function AI24AI_poll_for_response_and_retrieve_details($thread_id, $run_id) { $api_key = get_option('AI24AI_api_key'); // Retrieve API key $base_api_url = "https://api.openai.com/v1"; $polling_interval = 2; $max_attempts = 40; $attempt = 0; while ($attempt < $max_attempts) { $attempt++; $run_status_response = wp_remote_get("{$base_api_url}/threads/{$thread_id}/runs/{$run_id}", [ 'headers' => [ 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', 'OpenAI-Beta' => 'assistants=v2' ], 'timeout' => 15 // Adjust the timeout as needed ]); if (is_wp_error($run_status_response)) { error_log('Error retrieving run status: ' . $run_status_response->get_error_message()); break; // Exit the loop in case of error } $run_status_data = json_decode(wp_remote_retrieve_body($run_status_response), true); if (!isset($run_status_data['status'])) { error_log('Run status key not found in response.'); continue; // Continue polling if status key is missing } // Handle 'requires_action' status if ($run_status_data['status'] === 'requires_action') { if (file_exists(AI24AI_CHILD_FUNCTIONS_FILE)) { require_once AI24AI_CHILD_FUNCTIONS_FILE; } else { // Fallback to the original functions.php if the child file does not exist require_once AI24AI_PLUGIN_DIR . 'includes/functions.php'; } $tool_outputs = []; if (!empty($run_status_data['required_action']['submit_tool_outputs'])) { foreach ($run_status_data['required_action']['submit_tool_outputs']['tool_calls'] as $tool_call) { $function_name = $tool_call['function']['name']; $arguments = json_decode($tool_call['function']['arguments'], true); if (function_exists($function_name)) { $result = call_user_func_array($function_name, $arguments); $tool_outputs[] = [ 'tool_call_id' => $tool_call['id'], // Ensure output is a JSON string 'output' => is_array($result) ? wp_json_encode($result) : (string) $result ]; } else { error_log("Function $function_name does not exist"); $tool_outputs[] = [ 'tool_call_id' => $tool_call['id'], 'output' => ['error' => "Function $function_name does not exist"] ]; } } } // Submit tool outputs to OpenAI after processing all required actions if (!empty($tool_outputs)) { error_log('Final tool_outputs: ' . print_r($tool_outputs, true)); AI24AI_submit_tool_outputs_to_openai($thread_id, $run_id, $tool_outputs); } } // If the run is completed or in_progress, retrieve the steps if (isset($run_status_data['status']) && in_array($run_status_data['status'], ['completed', 'in_progress'])) { $steps_response = wp_remote_get("{$base_api_url}/threads/{$thread_id}/runs/{$run_id}/steps", [ 'headers' => [ 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', 'OpenAI-Beta' => 'assistants=v2' ], 'timeout' => 15 ]); if (is_wp_error($steps_response)) { error_log('Error retrieving steps: ' . $steps_response->get_error_message()); break; // Exit the loop in case of error } $steps_data = json_decode(wp_remote_retrieve_body($steps_response), true); foreach ($steps_data['data'] as $step) { } // If the run completed, retrieve messages and return if ($run_status_data['status'] === 'completed') { $messages_response = wp_remote_get("{$base_api_url}/threads/{$thread_id}/messages", [ 'headers' => [ 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', 'OpenAI-Beta' => 'assistants=v2' ], 'timeout' => 15 ]); if (is_wp_error($messages_response)) { error_log('Error retrieving messages: ' . $messages_response->get_error_message()); // Handle error appropriately } $messages_data = json_decode(wp_remote_retrieve_body($messages_response), true); $filtered_messages = []; foreach ($messages_data['data'] as $message) { foreach ($steps_data['data'] as $step) { if (strpos($step['id'], $message['id']) !== false) { $filtered_messages[] = $message; break; } } } // Process the messages if (isset($messages_data['data']) && !empty($messages_data['data'])) { $structured_messages = array_map(function($message) { if ($message['role'] === 'assistant') { if (is_array($message['content'])) { foreach ($message['content'] as &$contentItem) { if (isset($contentItem['text']['value'])) { $cleaned_content = AI24AI_clean_gpt_response($contentItem['text']['value']); $contentItem['text']['value'] = AI24AI_process_markdown_and_links($cleaned_content); } } } else { $cleaned_content = AI24AI_clean_gpt_response($message['content']); $message['content'] = AI24AI_process_markdown_and_links($cleaned_content); } } return $message; }, $messages_data['data']); wp_send_json_success(['thread_id' => $thread_id, 'messages' => $structured_messages]); } else { wp_send_json_error(['error' => 'No messages found.']); } } } elseif ($run_status_data['status'] === 'failed') { error_log("Run $run_id failed or was cancelled."); wp_send_json_error(['error' => 'Run failed or was cancelled.']); return; } sleep($polling_interval); } error_log("Run $run_id did not complete in expected time."); wp_send_json_error(['error' => 'Run did not complete in expected time2.']); } function AI24AI_submit_tool_outputs_to_openai($thread_id, $run_id, $tool_outputs) { $api_key = get_option('AI24AI_api_key'); $url = "https://api.openai.com/v1/threads/{$thread_id}/runs/{$run_id}/submit_tool_outputs"; $args = array( 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', 'OpenAI-Beta' => 'assistants=v2' ), 'body' => wp_json_encode(array('tool_outputs' => $tool_outputs)), // Make sure tool_outputs are formatted correctly 'method' => 'POST', 'data_format' => 'body', ); $response = wp_remote_post($url, $args); if (is_wp_error($response)) { $error_message = $response->get_error_message(); error_log("Error submitting tool outputs: $error_message"); } else { $response_code = wp_remote_retrieve_response_code($response); $response_body = wp_remote_retrieve_body($response); //error_log("Response from OpenAI: HTTP Status Code {$response_code}, Response: {$response_body}"); if ($response_code != 200) { error_log("Failed to submit tool outputs: HTTP Status Code {$response_code}, Response: {$response_body}"); } } }