Creating Assistant with API and wordpress

Hello, i want to make a wordpress plugin wich creating an assistant. I have problem with that and can not figure out whats the problem. I got internal server error. I am pretty sure its a small mistake in code, but i cant figure out what is it…


function add_chat_icon_and_window() {
    $chatbot_profile_image = get_option('ai_chatbot_profile_image');
    $license_key = get_option('ai_chatbot_license_key');
    $license_check = check_license_status($license_key);
    $assistant_name = get_option('ai_chatbot_assistant_name', 'AI Asszisztens'); // Alapértelmezett név, ha nincs beállítva
    $welcome_message = get_option('ai_chatbot_welcome_message', 'Szia, én egy AI Chatbot vagyok!'); // Alapértelmezett üdvözlő üzenet, ha nincs beállítva

    // Ellenőrizze, hogy van-e érvényes liszensz
    if (is_wp_error($license_check)) {
        // Itt kezeljük a hibát, például naplózás vagy üzenet a felhasználónak
        error_log('Licenckulcs ellenőrzési hiba: ' . $license_check->get_error_message());
        // Itt dönthet úgy, hogy nem jelenít meg semmit, vagy hibaüzenetet jelenít meg a felhasználónak
        return;
    }
    $favicon_url = get_site_icon_url( 50 ); // 50x50 pixel méretben
    $chat_logo = get_option('ai_chatbot_chat_logo'); // Kép URL lekérése

    // Ha nincs beállítva chat logó, használja a favicon-t
    if (empty($chat_logo)) {
        $chat_logo = $favicon_url;
    }

    // Ellenőrizzük, hogy van-e érvényes kép URL
    if (empty($chat_logo)) {
        $chat_logo = 'fallback_chat_logo_url'; // Alapértelmezett chat logó URL, ha nincs beállítva és nincs favicon
    }

    ?>
    <style>
        .chatbot-message img {
    width: 40px;
    height: 40px;
    border-radius: 20px;
    margin-right: 10px;
}
        :focus-visible {
    outline: -webkit-focus-ring-color auto 0px!important;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

#spinner {
    display: none;
    text-align: center;
}

.spinner {
    border: 4px solid #f3f3f3; /* Világosszürke */
    border-top: 4px solid #3498db; /* Kék */
    border-radius: 50%;
    width: 20px;
    height: 20px;
    animation: spin 2s linear infinite;
    display: inline-block; /* Biztosítja, hogy középen legyen */
}
#chat-window {
    z-index: 99999;
    position: fixed;
    bottom: 70px;
    right: 20px;
    width: 400px;
    min-height: 550px;
    background: white;
    box-shadow: 0px 0px 10px 0px rgba(0,0,0,0.5);
    overflow-y: auto;
    padding: 10px;
}


    #chat-window .chatbot-message {
        margin: 10px 0;
        padding: 5px;
        background-color: #f1f1f1;
        border-radius: 5px;
        display:flex;
    }
#chat-window .user-input {
    position: fixed;
    bottom: 0;
    right: 20px;
    width: 400px;
    background: white;
    box-shadow: 0px 0px 10px 0px rgba(0,0,0,0.5);
    padding: 10px;
    display: flex;
	    z-index: 99999;
}
#close-chat {
    position: absolute;
    top: 5px;
    right: 40px!important;
    cursor: pointer;
    font-size: 16px; /* Ha szöveges "X"-et használ */
    color: #333; /* Szöveg színe */
}
#chat-messages {
	
}
    </style>
    <div id="chat-icon" style="position: fixed; bottom: 50px; right: 80px; cursor: pointer; z-index: 99999; display: flex; align-items: center; background-color: white; border: 1px solid #ccc; border-radius: 5px; padding: 5px;align-items: flex-end;">
        <img src="<?php echo esc_url( $chat_logo ); ?>" alt="Chat" style="width: 50px; height: 50px;"> <!-- Chat logó vagy Favicon -->
        <h6 style="margin-left: 10px;"><?php echo esc_html($assistant_name); ?></h6>
    </div>
    <div id="chat-window" style="position: fixed; bottom: 50px; right: 20px; z-index: 99999; background-color: white; border: 1px solid #ccc; padding: 10px; display: none; max-width: 500px;">
        <div id="close-chat" style="position: absolute; top: 5px; right: 10px; cursor: pointer;">
            <i class="fa fa-times" aria-hidden="true"></i> <!-- Font Awesome X ikon -->
        </div>
        <div id="chat-messages" style="max-height: 500px; overflow-y: auto; padding: 5px;">
           
        </div>
        <div id="spinner" style="display: none; text-align: center; margin: 10px 0;">
            <div class="spinner" style="margin: auto;"></div>
        </div>

                <div class="user-input" style="padding: 5px; text-align: center;">
            <input type="text" id="user-message" placeholder="Írd be az üzeneted..." style="width: 60%; padding: 5px; margin-right: 5px;">
            <button onclick="sendMessage()" style="width: 15%; padding: 5px; margin-right: 5px;">
                <i class="fa fa-paper-plane" aria-hidden="true"></i> <!-- Küldés ikon -->
            </button>
            <button id="clear-chat" style="width: 15%; padding: 5px;">
                <i class="fa fa-trash" aria-hidden="true"></i> <!-- Trash ikon -->
            </button>
        </div>

    </div>
    <script>

                    function saveChatMessages() {
                        var chatMessages = document.querySelectorAll('#chat-messages .chatbot-message, #chat-messages .user-message');
                        var messages = Array.from(chatMessages).map(div => ({
                            className: div.className,
                            content: div.innerText
                        }));
                        localStorage.setItem('chatMessages', JSON.stringify(messages));
            }
                    function generateNewChatId() {
                        var newChatId = Date.now().toString(); // Egyedi ID generálása a jelenlegi időbélyeg alapján
                        localStorage.setItem('chatId', newChatId); // Az új chat ID tárolása a localStorage-ban
                        return newChatId;
                    }
                    function getChatId() {
                        return localStorage.getItem('chatId') || generateNewChatId();
                    }
                     function startNewChat() {
                        generateNewChatId(); // Új chat ID generálása
                        clearChat(); // A jelenlegi chat üzenetek törlése
                        // További logika az új chat kezdéséhez...
                    }   
                     
                    function clearChat() {
                        generateNewChatId(); // Új chat ID generálása
                        localStorage.removeItem('chatMessages');
                        var chatMessagesDiv = document.getElementById('chat-messages');
                        chatMessagesDiv.innerHTML = '';
                        // Kezdeti üdvözlő üzenet hozzáadása
                        var chatbotGreeting = document.createElement('div');
                        chatbotGreeting.className = 'chatbot-message';
                        chatbotGreeting.innerHTML = '<span><?php echo esc_js($welcome_message); ?></span>';
                        chatMessagesDiv.appendChild(chatbotGreeting);
                    }

                    document.getElementById('clear-chat').addEventListener('click', function() {
                        clearChat();
                    });



  function sendMessage() {
    var chatId = getChatId();
    var xhr = new XMLHttpRequest();
    var userMessage = document.getElementById('user-message').value;
    var chatMessages = document.getElementById('chat-messages');
    var userMessageDiv = document.createElement('div');
    userMessageDiv.className = 'user-message';
    userMessageDiv.innerHTML = '<span>' + userMessage + '</span>';
    chatMessages.appendChild(userMessageDiv);

    document.getElementById('user-message').value = ''; // Üzenetmező kiürítése
    var spinner = document.getElementById('spinner');
    spinner.style.display = 'block';

    var postData = 'action=send_message_to_chatbot&message=' + encodeURIComponent(userMessage) + '&chat_id=' + chatId;
    console.log("Küldött adatok: ", postData);

    xhr.open('POST', '<?php echo admin_url('admin-ajax.php'); ?>', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    xhr.onload = function() {
        spinner.style.display = 'none';
        console.log("XHR állapotkód: ", this.status, ", Állapot szövege: ", this.statusText);
        if (this.status == 200) {
                    var response = JSON.parse(this.responseText);
                    if (response.success && response.data) {
                        var botMessageDiv = document.createElement('div');
                        botMessageDiv.className = 'chatbot-message';

                        // Profilkép hozzáadása, ha van beállítva
                        var profileImageURL = '<?php echo esc_js($chatbot_profile_image); ?>';
                        if (profileImageURL) {
                            var img = document.createElement('img');
                            img.src = profileImageURL;
                            img.className = 'profile-image';
                            botMessageDiv.appendChild(img);
                            localStorage.setItem('chatbotProfileImage', profileImageURL);
                        } else {
                            console.log('Nincs beállítva profilkép.');
                        }
                        // Szöveges válasz hozzáadása
                        var textSpan = document.createElement('span');
                        textSpan.innerText = response.data;
                        botMessageDiv.appendChild(textSpan);

                        chatMessages.appendChild(botMessageDiv);
                        chatMessages.scrollTop = chatMessages.scrollHeight;
                        saveChatMessages();

                        saveChatToDatabase(chatId, userMessage, response.data);
                    } else {
                        console.log("Hibás válasz: ", response);
                    }
                } else {
                    console.log("Hiba a kérés feldolgozásakor, állapotkód: ", this.status);
                    console.log("Teljes válasz: ", this.responseText);

                  }
    };

    xhr.onerror = function() {
        console.log("Hálózati hiba történt.");
    };

    xhr.ontimeout = function() {
        console.log("A kérés időtúllépés miatt megszakadt.");
    };

    xhr.onreadystatechange = function() {
        console.log("Kérés állapota változott: ", this.readyState);
    };

    xhr.timeout = 10000; // 10 másodperc időtúllépés
    xhr.send(postData);
}

function restoreChatMessages() {
    var savedProfileImage = localStorage.getItem('chatbotProfileImage');    
    var savedMessages = localStorage.getItem('chatMessages');
    var chatMessagesDiv = document.getElementById('chat-messages');
    var chatWindow = document.getElementById('chat-window'); // Hozzáadva a chat-window referencia

    if (savedMessages) {
        var chatMessages = JSON.parse(savedMessages);
        var isFirstMessage = true;

        chatMessages.forEach(msg => {
            var div = document.createElement('div');
            div.className = msg.className;
            div.innerText = msg.content;
            chatMessagesDiv.appendChild(div);
            if (savedProfileImage && msg.className.includes('chatbot-message') && !isFirstMessage) {
                var img = document.createElement('img');
                img.src = savedProfileImage;
                img.className = 'profile-image';
                div.insertBefore(img, div.firstChild);
            }

            chatMessagesDiv.appendChild(div);
            isFirstMessage = false;
        });
    } else {
        var chatbotGreeting = document.createElement('div');
        chatbotGreeting.className = 'chatbot-message';
        chatbotGreeting.innerHTML = '<span><?php echo esc_js($welcome_message); ?></span>';
        chatMessagesDiv.appendChild(chatbotGreeting);
    }

    chatMessagesDiv.scrollTop = chatMessagesDiv.scrollHeight;
    chatWindow.scrollTop = chatWindow.scrollHeight;
}


                
 function saveChatToDatabase(chatId, userMessage, botResponse) {
    jQuery.post(
        '<?php echo admin_url('admin-ajax.php'); ?>',
        {
            'action': 'ai_chatbot_save_chat_message',
            'chat_id': chatId,
            'message_type': 'user',
            'message_content': userMessage
        },
        function(response) {
            console.log('Felhasználói üzenet mentése: ', response);
        }
    );

    jQuery.post(
        '<?php echo admin_url('admin-ajax.php'); ?>',
        {
            'action': 'ai_chatbot_save_chat_message',
            'chat_id': chatId,
            'message_type': 'bot',
            'message_content': botResponse
        },
        function(response) {
            console.log('Bot válaszának mentése: ', response);
        }
    );
}




                document.getElementById('clear-chat').addEventListener('click', function() {
                    clearChat();
                });

                document.addEventListener('DOMContentLoaded', function() {
                    restoreChatMessages();
                });

                // Chat ablak megnyitásakor a legutolsó üzenetre görget
                document.getElementById('chat-icon').addEventListener('click', function() {
    var chatWindow = document.getElementById('chat-window');
    var chatMessagesDiv = document.getElementById('chat-messages');
    chatWindow.style.display = chatWindow.style.display === 'none' ? 'block' : 'none';

    // Görgetés a chat-messages div-en belül az üzenetek aljára
    setTimeout(function() {
        chatMessagesDiv.scrollTop = chatMessagesDiv.scrollHeight;
    }, 100);

    // Görgetés a chat-window div-en belül az aljára
    setTimeout(function() {
        chatWindow.scrollTop = chatWindow.scrollHeight;
    }, 100);
});




                document.getElementById('user-message').addEventListener('keypress', function(event) {
                    if (event.key === 'Enter') {
                        event.preventDefault();
                        sendMessage();
                    }
                });

                document.getElementById('close-chat').addEventListener('click', function() {
                    document.getElementById('chat-window').style.display = 'none';
                });
</script>


    <?php
}
add_action('wp_footer', 'add_chat_icon_and_window');

function handle_send_message_to_chatbot() {
    global $wpdb;
    $message = sanitize_text_field($_POST['message']);
    $api_key = get_option('ai_chatbot_api_key');
    $model = get_option('ai_chatbot_model');
    $assistant_creation_enabled = get_option('ai_chatbot_enable_assistant');
    $messages = array();
    $assistant_id = get_option('ai_chatbot_assistant_id');
    $thread_id = get_option('ai_chatbot_thread_id');


    error_log("Received message: " . $message);

if ($assistant_creation_enabled) {
               if (empty($assistant_id)) {
            wp_send_json_error('Az asszisztens ID nem található.');
            return;
        }

        if (empty($thread_id)) {
            $thread = create_openai_thread($api_key, [['role' => 'user', 'content' => $message]]);
            if (is_wp_error($thread)) {
                wp_send_json_error($thread->get_error_message());
                return;
            }
            $thread_id = $thread['id'];
            update_option('ai_chatbot_thread_id', $thread_id);
        }

        // Üzenet hozzáadása a threadhez
        $message_addition_response = add_message_to_thread($api_key, $thread_id, $message);
        if (is_wp_error($message_addition_response)) {
            wp_send_json_error('Üzenet hozzáadása a threadhez sikertelen.');
            return;
        }

        // Asszisztens futtatása
        $assistant_run_response = run_assistant_on_thread($api_key, $thread_id, $assistant_id);
        if (is_wp_error($assistant_run_response)) {
            wp_send_json_error('Asszisztens futtatása sikertelen.');
            return;
        }

        if ($assistant_run_response['status'] === 'completed') {
            $chat_response = retrieve_response($thread_id);
            wp_send_json_success($chat_response);
        } else {
            wp_send_json_error('A futtatás még nem fejeződött be.');
        }
    } else {
        // Az asszisztens létrehozása nélkül az összes releváns adatot hozzáadjuk
        $website_description = get_option('ai_chatbot_website_description');
        $qa_pairs = get_option('ai_chatbot_qa_pairs', array());
        if (!empty($website_description)) {
            $messages[] = array('role' => 'system', 'content' => $website_description);
        }
        foreach ($qa_pairs as $pair) {
            if (!empty($pair['question']) && !empty($pair['answer'])) {
                $messages[] = array('role' => 'system', 'content' => "Ha valaki kérdezi a " . $pair['question'] . "-ről, akkor ez a válasz: " . $pair['answer']);
            }
        }
        $custom_data_posts = $wpdb->get_results("SELECT * FROM $table_name LIMIT 1");
        foreach ($custom_data_posts as $custom_post) {
            $messages[] = array('role' => 'system', 'content' => "A(z) {$custom_post->post_type} típusú '{$custom_post->post_title}' tartalma: {$custom_post->post_content}");
        }
        $messages[] = array('role' => 'user', 'content' => $message);
        if ($model == 'gpt-4-0314' || $model == 'gpt-3.5-turbo') {
            $endpoint = 'https://api.openai.com/v1/chat/completions';
            $payload = array(
                'model' => $model,
                'messages' => $messages
            );
        }
    }

    $response = wp_remote_post($endpoint, array(
        'headers' => array(
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type' => 'application/json',
            'OpenAI-Beta' => 'assistants=v1'
        ),
        'body' => json_encode($payload),
        'timeout' => 65,
    ));

    if (is_wp_error($response)) {
        wp_send_json_error($response->get_error_message());
        return $response; // Hiba kezelése
    } else {
        $body = wp_remote_retrieve_body($response);
        error_log('OpenAI Response: ' . $body);
        $decoded_body = json_decode($body, true);
        if (isset($decoded_body['error'])) {
        error_log('Hibaüzenet: ' . $decoded_body['error']['message']);
        error_log('Hibatípus: ' . $decoded_body['error']['type']);
    }
        $chat_response = isset($decoded_body['choices'][0]['message']['content']) ? $decoded_body['choices'][0]['message']['content'] : '';
        wp_send_json_success($chat_response);
    }
}
add_action('wp_ajax_send_message_to_chatbot', 'handle_send_message_to_chatbot');
add_action('wp_ajax_nopriv_send_message_to_chatbot', 'handle_send_message_to_chatbot');




function ai_chatbot_create_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'ai_chatbot_chats';

    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        chat_id bigint(20) NOT NULL,
        message_type varchar(10) NOT NULL,
        message_content text NOT NULL,
        message_time datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

register_activation_hook(__FILE__, 'ai_chatbot_create_table');

function ai_chatbot_save_chat_message($chat_id, $message_type, $message_content) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'ai_chatbot_chats';

    // Validáció és tisztítás
    $chat_id = intval($chat_id); // Ez biztosítja, hogy a chat_id szám legyen
    $message_type = sanitize_text_field($message_type);
    $message_content = sanitize_text_field($message_content);

    // Ellenőrzés, hogy a chat_id nem üres és érvényes
    if (empty($chat_id)) {
        error_log("Hiba: Üres chat_id az adatbázisba mentés során.");
        return; // Ne folytassa, ha az chat_id üres
    }

    // Adatok beszúrása az adatbázisba
    $result = $wpdb->insert(
        $table_name,
        array(
            'chat_id' => $chat_id,
            'message_type' => $message_type,
            'message_content' => $message_content,
            'message_time' => current_time('mysql')
        )
    );

    // Ellenőrizzük, hogy sikeres volt-e a mentés
    if ($result) {
        error_log("Sikeres mentés az adatbázisba: Chat ID: $chat_id");
    } else {
        error_log("Hiba az adatbázisba mentés során: " . $wpdb->last_error);
    }
}



function ai_chatbot_handle_ajax_save_chat_message() {
    // Ellenőrizzük, hogy a szükséges adatok rendelkezésre állnak-e
    if (isset($_POST['chat_id'], $_POST['message_type'], $_POST['message_content'])) {
        $chat_id = intval($_POST['chat_id']);
        $message_type = sanitize_text_field($_POST['message_type']);
        $message_content = sanitize_text_field($_POST['message_content']);

        // Hívjuk meg a mentési függvényt az adatokkal
        ai_chatbot_save_chat_message($chat_id, $message_type, $message_content);

        // Sikeres válasz küldése
        wp_send_json_success('Üzenet sikeresen elmentve.');
    } else {
        // Hiba válasz, ha hiányoznak az adatok
        wp_send_json_error('Hiányzó adatok.');
    }
}
add_action('wp_ajax_ai_chatbot_save_chat_message', 'ai_chatbot_handle_ajax_save_chat_message');
add_action('wp_ajax_nopriv_ai_chatbot_save_chat_message', 'ai_chatbot_handle_ajax_save_chat_message');

function add_font_awesome() {
    wp_enqueue_style('font-awesome', '//cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css');
}
add_action('wp_enqueue_scripts', 'add_font_awesome');



function create_openai_assistant() {
    $api_key = get_option('ai_chatbot_api_key');
    if (empty($api_key)) {
        error_log('OpenAI Assistant Creation Failed: No API key provided.');
        return new WP_Error('no_api_key', 'OpenAI API kulcs szükséges.');
    }

    $assistant_name = get_option('ai_chatbot_assistant_name');
        $model = get_option('ai_chatbot_model'); // A modell a WordPress admin felületen kiválasztott modell

    if (empty($assistant_name)) {
        error_log('OpenAI Assistant Creation Failed: No assistant name provided.');
        return new WP_Error('no_assistant_name', 'Az asszisztens neve szükséges.');
    }

    $url = 'https://api.openai.com/v1/assistants';
    $body = array('name' => $assistant_name, 'model' => $model);
    $args = array(
        'headers' => array(
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type' => 'application/json',
            'OpenAI-Beta' => 'assistants=v1'
        ),
        'body' => json_encode($body),
        'method' => 'POST'
    );

    // Naplózás az API hívás adatairól
    error_log('Sending request to: ' . $url);
    error_log('Request body: ' . json_encode($body));

    $response = wp_remote_request($url, $args);

    if (is_wp_error($response)) {
        error_log('OpenAI Assistant Creation Failed: ' . $response->get_error_message());
        return $response;
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    if (isset($data['id'])) {
        $assistant_id = $data['id'];
        error_log('OpenAI Assistant Created Successfully: ' . $assistant_id);
        update_option('ai_chatbot_assistant_id', $assistant_id);
        // További műveletek az asszisztens ID-jével
        return $assistant_id;
    } else {
        error_log('OpenAI Assistant Creation Failed: Assistant ID not retrieved.');
        return new WP_Error('no_assistant_id', 'Nem sikerült kinyerni az asszisztens ID-jét.');
    }
}


function create_openai_thread($api_key, $initial_messages) {
    $url = 'https://api.openai.com/v1/threads';
    $args = array(
        'headers' => array(
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type' => 'application/json',
            'OpenAI-Beta' => 'assistants=v1'  // Helyes fejléc hozzáadása
        ),
        'body' => json_encode(array('messages' => $initial_messages)),
        'method' => 'POST'
    );

    $response = wp_remote_request($url, $args);

    if (is_wp_error($response)) {
        return $response;
    }

    $body = wp_remote_retrieve_body($response);
    return json_decode($body, true);
}


function check_run_status($run_id) {
    $api_key = get_option('ai_chatbot_api_key');

    if (empty($api_key)) {
        error_log('API key is missing.');
        return;
    }

    $url = 'https://api.openai.com/v1/threads/runs/' . $run_id;
    $args = array(
        'headers' => array(
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type' => 'application/json',
            'OpenAI-Beta' => 'assistants=v1'
        ),
        'method' => 'GET'
    );

    $response = wp_remote_request($url, $args);

    if (is_wp_error($response)) {
        error_log('Error checking run status: ' . $response->get_error_message());
        return;
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    if (isset($data['status'])) {
        error_log('Run status: ' . $data['status']);
        return $data['status'];
    } else {
        error_log('Failed to retrieve run status.');
        return 'error';
    }
}
function retrieve_response($thread_id) {
    $api_key = get_option('ai_chatbot_api_key');

    if (empty($api_key)) {
        error_log('API key is missing.');
        return;
    }

    $url = 'https://api.openai.com/v1/threads/' . $thread_id . '/messages';
    $args = array(
        'headers' => array(
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type' => 'application/json',
            'OpenAI-Beta' => 'assistants=v1'
        ),
        'method' => 'GET'
    );

    $response = wp_remote_request($url, $args);

    if (is_wp_error($response)) {
        error_log('Error retrieving response: ' . $response->get_error_message());
        return;
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    if (isset($data['data'])) {
        foreach ($data['data'] as $message) {
            if ($message['role'] === 'assistant') {
                // Itt található az asszisztens által küldött válasz
                error_log('Assistant response: ' . $message['content']); // Logolás hozzáadása
                return $message['content'];
            }
        }
    }

    error_log('No response found in the thread.');
    return 'No response';
}
function initiate_run($api_key, $thread_id, $assistant_id) {
    // Ellenőrizzük, hogy a szükséges paraméterek érvényesek-e
    if (empty($api_key) || empty($thread_id) || empty($assistant_id)) {
        error_log('Run initiation failed: Missing required parameters.');
        return new WP_Error('missing_parameters', 'Hiányzó szükséges paraméterek.');
    }

    $url = 'https://api.openai.com/v1/threads/' . $thread_id . '/runs'; // Ellenőrizd, hogy ez az URL helyes-e

    $payload = json_encode(array('model' => $assistant_id)); // A payload lehet, hogy módosításra szorul

    $args = array(
        'headers' => array(
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type' => 'application/json'
        ),
        'body' => $payload,
        'method' => 'POST'
    );

    $response = wp_remote_request($url, $args);

    // Hibakezelés
    if (is_wp_error($response)) {
        error_log('Run initiation failed: ' . $response->get_error_message());
        return $response;
    }

    $http_code = wp_remote_retrieve_response_code($response);
    if ($http_code != 200) {
        error_log('Run initiation failed with HTTP code: ' . $http_code);
        return new WP_Error('http_error', 'HTTP hiba történt: ' . $http_code);
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    if (!isset($data['id'])) {
        error_log('Run initiation failed: No run ID retrieved.');
        return new WP_Error('no_run_id', 'Nem sikerült kinyerni a futás ID-jét.');
    }

    // Sikeres válasz kezelése
    return $data;
}
function add_message_to_thread($api_key, $thread_id, $message, $role = 'user') {
    $url = "https://api.openai.com/v1/threads/$thread_id/messages";

    $args = array(
        'headers' => array(
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type' => 'application/json',
            'OpenAI-Beta' => 'assistants=v1'
        ),
        'body' => json_encode(array(
            'role' => $role,
            'content' => $message
        )),
        'method' => 'POST'
    );

    $response = wp_remote_request($url, $args);

    if (is_wp_error($response)) {
        error_log('Hiba az üzenet threadhez adásakor: ' . $response->get_error_message());
        return $response;
    }

    return wp_remote_retrieve_body($response);
}
function run_assistant_on_thread($api_key, $thread_id, $assistant_id) {
    $url = "https://api.openai.com/v1/threads/$thread_id/runs";

    $args = array(
        'headers' => array(
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type' => 'application/json'
        ),
        'body' => json_encode(array('assistant_id' => $assistant_id)),
        'method' => 'POST'
    );

    $response = wp_remote_request($url, $args);

    if (is_wp_error($response)) {
        error_log('Hiba az asszisztens futtatásakor: ' . $response->get_error_message());
        return $response;
    }

    return wp_remote_retrieve_body($response);
}

Welcome to the forum.

Have you checked your error logs? That might provide more info. Here’s what GPT-4 had to say…

To troubleshoot the issue of an internal server error in your WordPress plugin, we need to consider several potential causes. Here’s a step-by-step guide to help you diagnose and fix the issue:

1. Check Error Logs

  • Access Server Logs: Look at your server’s error logs to see if there are any specific error messages related to the plugin.
  • Enable WP_DEBUG: If you haven’t already, enable WP_DEBUG in your wp-config.php file. This can provide more detailed error messages.

2. Examine Specific Functions

  • handle_send_message_to_chatbot Function: This function is critical as it handles the AJAX request. Ensure it’s correctly receiving and processing the data.
  • Error Handling: Check how errors are handled in your AJAX functions. Ensure that errors are correctly captured and logged.

3. Validate Data and Sanitization

  • Make sure all data is correctly sanitized and validated before being used. Incorrect data handling can lead to errors.

4. Plugin Activation Hook

  • ai_chatbot_create_table Function: Ensure that this function correctly creates the necessary database table without errors. Issues here could lead to problems when the plugin tries to interact with the database.

5. External API Integration

  • If your plugin interacts with external APIs (like OpenAI), make sure that:
    • The API keys are correct and have the necessary permissions.
    • The API endpoints are correctly formatted.
    • The server can make outgoing HTTP requests.

6. JavaScript and AJAX Calls

  • Review the AJAX calls in your JavaScript code. Make sure that:
    • The URLs are correct.
    • Data is being sent and received correctly.
    • There are no JavaScript errors that might prevent AJAX calls.

7. PHP Version Compatibility

  • Check if your PHP code is compatible with the PHP version running on your WordPress server.

8. Plugin Conflicts

  • Deactivate Other Plugins: Sometimes, conflicts with other plugins can cause issues. Try deactivating other plugins temporarily to see if the problem persists.

9. WordPress and Server Configuration

  • Ensure that your WordPress setup and server configuration meet the requirements of your plugin.

10. Syntax and Semantic Errors

  • Recheck your code for any syntax or semantic errors that might have been overlooked.

Debugging Tips:

  • Isolate the Problem: Comment out sections of your code and reintroduce them one by one to isolate where the error occurs.
  • Logging: Add more logging statements to trace the flow of data and identify where the failure happens.

Next Steps:

  • Once you identify the specific area causing the error, you can focus on fixing that part of the code.
  • If you’re unable to find the error, consider sharing specific error messages or code snippets for more targeted assistance.

Remember, internal server errors can be caused by a wide range of issues, so a systematic approach to debugging is key.

1 Like